题目:
给定一棵二叉查找树和一个新的树节点,将节点插入到树中。
你需要保证该树仍然是一棵二叉查找树。
样例
给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:
挑战
能否不使用递归?
解题:
递归的方法比较简单
Java程序:
/** * 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) 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; } }
View Code
总耗时: 1636 ms
非递归的感觉比较复杂。。。。
一直非递归的方法,就是一直走,一直走,走到没有路的时候就是插入的节点,这里是因为插入的节点一定是在新建的叶子节点,原理是二叉查找树是;1,根节点左子树的值比根节点小,右子树的值都比根节点大,2.左右子树也满足1的条件
下面程序定义的slow指针是用来做最后插入节点的父节点的
/** * 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 fast = root; TreeNode slow = null; while(fast!=null){// fast == null 的时候 slow就是其父结点,而这个空的就是要插入的结点位置 slow = fast; if(fast.val>node.val){ fast = fast.left; }else{ fast = fast.right; } } if(slow!=null){ if(slow.val>node.val){ slow.left = node; }else{ slow.right = node; } } return root; } }
总耗时: 1753 ms
Python程序:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ 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. """ def insertNode(self, root, node): # write your code here if root==None: return node if root.val>=node.val: root.left = self.insertNode(root.left,node) if root.val<node.val: root.right = self.insertNode(root.right,node) return root
View Code
总耗时: 272 ms
非递归程序:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ 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. """ def insertNode(self, root, node): # write your code here cur = root last = None if root==None: return node while cur!=None: last = cur if cur.val>node.val: cur = cur.left elif cur.val<=node.val: cur = cur.right if last!=None: if last.val>node.val: last.left = node else: last.right = node return root
View Code