问题描述:
给定一颗二叉查找树和一个新的树节点,将节点插入到树中。你需要保证该树仍是一颗二叉查找树。
实现思路:
利用递归,如果该节点的值大于根节点的值插入右子树,否则插入左子树。
代码:
/**
* Definition of TreeNode:* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: The root of the binary search tree.
* @param node: insert this node into the binary search tree
* @return: The root of the new binary search tree.
*/
TreeNode* insertNode(TreeNode* root, TreeNode* node) {
// write your code here
if(root==NULL)
return node;
else if(node->val>root->val) root->right=insertNode(root->right,node);
else root->left=insertNode(root->left,node);
return root;
}
};
感想:
利用递归,根据节点值进行比较找到合适的位置
本文介绍了一种在二叉查找树中插入新节点的方法,通过递归算法确保树的特性得以保持。当新节点的值大于当前节点值时,将其插入右子树;反之,则插入左子树。

被折叠的 条评论
为什么被折叠?



