Given A binary search tree new tree node, insert the node into the tree. You should keep the tree still is a valid binary search tree. Examplegiven binary search tree as follow: 2 / 1 4 / 36, the Tree should be: 2 / 1 4 / \ 3 6 Challengedo it without recursion
Recursion procedure:
1 Public classSolution {2 /**3 * @paramroot:the root of the binary search tree.4 * @paramNode:insert This node into the binary search tree5 * @return: The root of the new binary search tree.6 */7 PublicTreeNode Insertnode (TreeNode root, TreeNode node) {8 //Write your code here9 if(Root = =NULL)returnnode;Ten if(node = =NULL)returnRoot; OneTreeNode rootcopy =Root; A while(Root! =NULL) { - if(Root.val<=node.val && root.right==NULL) { -Root.right =node; the Break; - } - Else if(Root.val>node.val && root.left==NULL) { -Root.left =node; + Break; - } + Else if(Root.val <= node.val) root =Root.right; A ElseRoot =Root.left; at } - returnrootcopy; - } -}
Iterative procedure:
1 Public classSolution {2 /**3 * @paramroot:the root of the binary search tree.4 * @paramNode:insert This node into the binary search tree5 * @return: The root of the new binary search tree.6 */7 PublicTreeNode Insertnode (TreeNode root, TreeNode node) {8 //Write your code here9 if(Root = =NULL)returnnode;Ten if(node = =NULL)returnRoot; OneTreeNode rootcopy =Root; A while(Root! =NULL) { - if(Root.val<=node.val && root.right==NULL) { -Root.right =node; the Break; - } - Else if(Root.val>node.val && root.left==NULL) { -Root.left =node; + Break; - } + Else if(Root.val <= node.val) root =Root.right; A ElseRoot =Root.left; at } - returnrootcopy; - } -}
Lintcode:insert Node in a Binary Search Tree