在二叉查找树中插入节点

来源:互联网 发布:ug8.0数控编程实例 编辑:程序博客网 时间:2024/05/17 10:06

1.问题描述

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

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

 注意事项

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

样例

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

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

2.解题思路

如果树为空,直接生成一棵只有根节点的树,树不为空时,判断节点与根节点的大小,然后按大小递归左右子树,最后返回头结点。

3.代码实现

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

4.感想

注意在递归时,根据前提条件将递归结果复制给当前节点的左右子树。

0 0
原创粉丝点击