85. 在二叉查找樹中插入節(jié)點
給定一棵二叉查找樹和一個新的樹節(jié)點拗秘,將節(jié)點插入到樹中圣絮。
你需要保證該樹仍然是一棵二叉查找樹。
注意事項
You can assume there is no duplicate values in this tree + node.
您在真實的面試中是否遇到過這個題雕旨?
Yes
樣例
給出如下一棵二叉查找樹扮匠,在插入節(jié)點6之后這棵二叉查找樹可以是這樣的:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
相關題目
AC代碼:
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;
}else if(root->val<=node->val){
root->right=insertNode(root->right,node);
}else{
root->left=insertNode(root->left,node);
}
return root;
}
};