题目描述:
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
Challenge
题目思路:
Can you do it without recursion?
这题不用recursion做的话,就还是用BFS的思路。因为是BST,所以可以有方向的往下(要么左子树,要么右子树)。当遇到null的时候,就把新node连上去。
Mycode(AC = 42ms):
/**
* 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;
queue<TreeNode *> helper;
helper.push(root);
while (!helper.empty()) {
TreeNode *tmp = helper.front();
helper.pop();
if (node->val > tmp->val) {
if (tmp->right) {
helper.push(tmp->right);
}
else {
tmp->right = node;
}
}
else {
if (tmp->left) {
helper.push(tmp->left);
}
else {
tmp->left = node;
}
}
}
return root;
}
};