在二叉查找树中插入节点

来源:互联网 发布:淘宝买药暗语 编辑:程序博客网 时间:2024/06/10 23:45

一、问题描述

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

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

 注意事项

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

样例

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

  2             2 / \           / \1   4   -->   1   4   /             / \   3             3   6
二、解题思路

    运用递归算法,插入给定节点,用root指针依此遍历二叉树并进行比较,当插入节点小于此时root指针指的节点则继续跟此根节点的左子树进行比较,若大于,再跟右子树比较。

三、我的代码

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) 
        {
            root=new TreeNode(node->val);
            return root;
        }
        else if(root->val>node->val)
        {
            root->left=insertNode(root->left,node);
            return root;
        }
        else
        {
            root->right=insertNode(root->right,node);
            return root;
        }
    }
};

四、我的感想

   再次运用递归算法,也说明了递归的重要性,可以大大简化问题,插入节点只需依此遍历二叉树比较大小然后判断插在哪即可。

0 0