題目
給定一棵二叉查找樹(shù)和一個(gè)新的樹(shù)節(jié)點(diǎn)怠惶,將節(jié)點(diǎn)插入到樹(shù)中涨缚。
你需要保證該樹(shù)仍然是一棵二叉查找樹(shù)。
分析
分別用遞歸和非遞歸兩種方法實(shí)現(xiàn)策治。本質(zhì)上會(huì)發(fā)現(xiàn)脓魏,兩種方法類似
public class Solution {
/**
* @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.
*/
public TreeNode insertNode(TreeNode root, TreeNode node) {
if(root == null)
return node;
if(root.val > node.val)
root.left = insertNode(root.left, node);
else
root.right = insertNode(root.right, node);
return root;
}
}
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @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.
*/
public TreeNode insertNode(TreeNode root, TreeNode node) {
// write your code here
if (root == null) {
root = node;
return root;
}
TreeNode tmp = root;
TreeNode last = null;
while (tmp != null) {
last = tmp;
if (tmp.val > node.val) {
tmp = tmp.left;
} else {
tmp = tmp.right;
}
}
if (last != null) {
if (last.val > node.val) {
last.left = node;
} else {
last.right = node;
}
}
return root;
}
}