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.
Can you do it without recursion?
递归
/**
* 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(node==NULL){
return root;
}
if(root==NULL){
return node;
}
if(node->val<root->val){
root->left=insertNode(root->left,node);
}else{
root->right=insertNode(root->right,node);
}
return root;
}
};
迭代
/**
* 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(node==NULL){
return root;
}
if(root==NULL){
return node;
}
TreeNode *tempNode=root;
while(tempNode){
if(node->val<tempNode->val){
if(tempNode->left==NULL){
tempNode->left=node;
return root;
}
tempNode=tempNode->left;
}else{
if(tempNode->right==NULL){
tempNode->right=node;
return root;
}
tempNode=tempNode->right;
}
}
return root;
}
};