标签:
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.
Given binary search tree as follow, after Insert node 6, the tree should be:
2 2
/ \ / 1 4 --> 1 4
/ / \
3 3 6
Can you do it without recursion?
SOLUTION 1:
首先从最好理解的recursion开始。
递归算法,1,首先这个输入跟我要做递归的函数input相同,所以没必要再做一个辅助函数,2,然后,再看递归具体步骤,从局部考虑,如果node.val > root.val 递归应该向右边进行(也就是说node一定会加在root右子树上),同理node.val < root.val ==>递归向左进行。3,最后考虑递归的结束条件是什么,这题的结束条件就是指针移动到一个没有左儿子或者右儿子的地方,把node加进去,返回这个结果 ==> 也就是root.left/right = node。
具体看代码:
/** * 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) { if (root == null){ return node; } if (root.val > node.val){ root.left = insertNode(root.left, node); } if (root.val < node.val){ root.right = insertNode(root.right, node); } return root; } }
SOLUTION 2:
非递归方法:
非递归就是说,找到root点,root左子树或者右子树是空的,选择性的把node放在上面。
/** * 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) { if (root == null){ return node; } if (node == null){ return root; } TreeNode current = root; while (current != null){ if (node.val > current.val && current.right == null){ current.right = node; break; } else if (node.val < current.val && current.left == null){ current.left = node; break; } else if (node.val > current.val){ current = current.right; } else { current = current.left; } } return root; } }
[Lintcode] Insert Node in a Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/tritritri/p/4937952.html