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
解题思路1:
递归。利用平衡二叉树的性质即可写出。
/** * 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 new TreeNode(node->val); if(root->val > node->val) { root->left = insertNode(root->left,node); } else //root->val < node->val { root->right = insertNode(root->right,node); } return root; } };
解题思路2:
非递归方法:双指针法。
/** * 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 TreeNode * cur = root;//指向需要插入节点的位置 TreeNode * pre = cur;//指向需要插入节点位置的父节点 //定位cur与pre的位置 while(cur != NULL) { if(cur->val > node->val) { pre = cur; cur = cur->left; } else { pre = cur; cur = cur->right; } } //定位好之后新建节点 cur = new TreeNode(node->val); //将新建的节点连接上pre,完成插入 if(pre == NULL) root = cur; else if(pre->val > node->val) pre->left = cur; else pre->right = cur; return root; } };