Insert Node in a Binary Search Tree
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. Example Given binary search tree as follow: / \ 4 / after Insert node 6, the tree should be: / \ 4 / \ 6 Challenge Do it without recursion
Iterative做法
public TreeNode insertNode(TreeNode root, TreeNode node) { // write your code here if (root == null) { return node; } // tmp 不断比较找到最后一个点, 用last记录 TreeNode tmp = root, last = null; while (tmp != null) { last = tmp; if (tmp.val > node.val) { tmp = tmp.left; } else { tmp = tmp.right; } } // 分情况讨论 将node 链接 if (last.val > node.val) { last.left = node; } else { last.right = node; } return root; }
分治法:
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; }
Recursion做法:
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) return node; if (node == null) return root; helper(root, node); return root; } public void helper(TreeNode root, TreeNode node) { if (root.val <= node.val && root.right == null) root.right = node; else if (root.val > node.val && root.left == null) root.left = node; else if (root.val <= node.val) helper(root.right, node); else helper(root.left, node); } }