描述
中文English
給定一棵二叉查找樹和一個新的樹節點,將節點插入到樹中。
你需要保證該樹仍然是一棵二叉查找樹。
保證不會出現重複的值
您在真實的面試中是否遇到過這個題? 是
題目糾錯
樣例
樣例 1:
輸入: tree = {}, node= 1
輸出: {1}
樣例解釋:
在空樹中插入一個點,應該插入爲根節點。
樣例 2:
輸入: tree = {2,1,4,3}, node = 6
輸出: {2,1,4,3,6}
樣例解釋:
如下:
2 2
/ \ / \
1 4 --> 1 4
/ / \
3 3 6
調了半個多小時 非遞歸的也沒寫出來
放棄了
/**
* 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.
*/
void dfs(TreeNode * root, TreeNode * node) {
if (root == NULL) {
root = node;
return;
}
if (root->val > node -> val) {
if (root->left)
dfs(root->left, node);
else {
root->left = node;
return;
}
} else {
if (root->right)
dfs(root->right, node);
else {
root->right = node;
return;
}
}
}
TreeNode * insertNode(TreeNode * root, TreeNode * node) {
// write your code here
if(root) {
dfs(root, node);
return root;
} else {
return node;
}
}
};