Given a binary search tree and a new tree node, insert the node into the tree. You should keep the tree still is a valid binary search tree.
Example
Given binary search tree as follow, after Insert node 6, the tree should is:
2 2 / \ / 1 4 --> 1 4 / / \ 3 3 6
Challenge
Can do it without recursion?
Both of these methods are written, recursive and non-recursive
1. Recursion
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:the root of the binary search tree. * @paramNode:insert This node into the binary search tree *@return: The root of the new binary search tree. */ PublicTreeNode Insertnode (TreeNode root, TreeNode node) {//Write your code here if(Root = =NULL) returnnode; if(Root.val = =node.val) { returnRoot; } if(Root.left = =NULL&& root.val >node.val) {Root.left=node; returnRoot; } if(Root.right = =NULL&& Root.val <node.val) {Root.right=node; returnRoot; } if(Root.val >node.val) {TreeNode Left=Insertnode (root.left, node); Root.left=Left ; } Else if(Root.val <node.val) {TreeNode Right=Insertnode (root.right, node); Root.right=Right ; } returnRoot; }}
2. Non-recursive
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:the root of the binary search tree. * @paramNode:insert This node into the binary search tree *@return: The root of the new binary search tree. */ PublicTreeNode Insertnode (TreeNode root, TreeNode node) {//Write your code here if(Root = =NULL) returnnode; if(Root.val = =node.val)returnRoot; TreeNode P=Root; while(! (P.left = =NULL&& p.val > Node.val) &&! (P.right = =NULL&& P.val <node.val)) { if(P.val >node.val) P=P.left; Else if(P.val = =node.val)returnRoot; ElseP=P.right; } if(P.left = =NULL&& p.val >node.val) {P.left=node; returnRoot; } Else{p.right=node; returnRoot; } }}
Lintcode-easy-insert Node in a Binary Search Tree