问题描述:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
递归解法:
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) {
if (NULL == root) {
return node;
}
if (node->val <= root->val) {
root->left = insertNode(root->left, node);
} else {
root->right = insertNode(root->right, node);
}
return root;
}
};
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(node==NULL){
return root;
}
if (root==NULL){
return node;
}
TreeNode* tmp = root, *last = root;
while (tmp){
last = tmp;
if (tmp->val>node->val){
tmp = tmp->left;
} else {
tmp = tmp->right;
}
}
if (last->val>node->val){
last->left = node;
} else {
last->right = node;
}
return root;
}
};