LintCode【简单】85. 在二叉查找树中插入节点。代码及思路

题目要求:

给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

你需要保证该树仍然是一棵二叉查找树。

 注意事项

You can assume there is no duplicate values in this tree + node.

样例

给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6

思路:

使用递归查找到适合的位置并插入。这里我犯了一个错误,我在递归函数里判断root是否为空,若为空,指向node,但是这个编译是不通过的。应该是找到他的根节点,使根节点的左或者右指针指向node。

这里注意当整个二叉树为空的时候,在函数里判断一下,直接return node就可以了。

代码:

/**
 * 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.
     */
    void serch(TreeNode * root, TreeNode * node){
        if(node->val > root->val){
            if(root->right == NULL){
                root->right = node;
                return;
            } 
            serch(root->right, node);
        }
        else{
            if(root->left == NULL){
                root->left = node;
                return;
            }
            serch(root->left, node);
        }
        return;
    }
    TreeNode * insertNode(TreeNode * root, TreeNode * node) {
        // write your code here
        if(root == NULL){
            root = node;
            return root;
        }
        serch(root, node);
        return root;
    }
};


猜你喜欢

转载自blog.csdn.net/limonsea/article/details/79296140
今日推荐