在二叉查找樹中插入節點-LintCode

描述:

給定一棵二叉查找樹和一個新的樹節點,將節點插入到樹中。

你需要保證該樹仍然是一棵二叉查找樹。

 注意事項

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

樣例:

給出如下一棵二叉查找樹,在插入節點6之後這棵二叉查找樹可以是這樣的:

  2             2
 / \           / \
1   4   -->   1   4
   /             / \ 
  3             3   6
思路:
若二叉排序樹爲空樹,則新插入的結點爲新的根節點;否則,新插入的結點必爲一個新的葉子結點。
這樣,我們就只需要比較給定node與根結點的值,從而選擇繼續訪問根結點的左子樹還是右子樹。
訪問到空位置,即插入node。
AC代碼:
/**
 * 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 insertNodeCore(TreeNode* root,TreeNode* node)
    {
        if(root->val > node->val && root->left==NULL)
           {
               root->left=node;
               return;
           }
        if(root->val < node->val && root->right==NULL)
           {
               root->right=node;
               return;
           }
        if(root->val > node->val)
            insertNodeCore(root->left,node);
        else
            insertNodeCore(root->right,node);
        
    }
    
    TreeNode* insertNode(TreeNode* root, TreeNode* node) {
        // write your code here
        if(root==NULL)
        return node;
        insertNodeCore(root,node);
        return root;
    
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章