在二叉查找树中插入节点

来源:互联网 发布:ps4数据库损坏 编辑:程序博客网 时间:2024/05/16 08:14

问题描述:

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

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

样例

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

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

运用递归调用和查找树的特点,值比根节点大的在左子树,比根节点小的在右子树

代码:

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

感想:

注意要把递归的结果记录下来

原创粉丝点击