在二叉树中插入节点

Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

 Notice

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

Example

Given binary search tree as follow, after Insert node 6, the tree should be:

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

 

posted @ 2017-06-12 17:16  mximo  阅读(297)  评论(0编辑  收藏  举报