lintcode 85 在二叉树中插入节点

来源:互联网 发布:win10禁用windows键 编辑:程序博客网 时间:2024/06/03 13:35
1.

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

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

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

4.比较简单的一道题.,能通过老师讲的思路做出来

原创粉丝点击