给定一个node,找inorder traversal 里下一个。
最直接的想法是inorder遍历整个bst,然后在遍历的结果中查找。但是这样耗费多余的空间和时间。
(1)有parent指针
在cc150上有很好的讲解
三种情况:
i 当前node的right != null, 则返回leftmost of right subtree
ii 当前node.right == null
如果node为其parent的左孩子,则可以直接返回node.parent
如果node为其parent右孩子,则一直向上走直到node在parent left subtree
Node inorderSucc(Node n){ if(n has a right subtree){ return leftmost child of right subtree }else{ while(n is a right child of n.parent){ n = n.parent; // go up } return n.parent; // Parent has not been traversed } }
实际代码:
1 public static TreeNode inorderNext(TreeNode node){ 2 if(node == null) return null; 3 4 if(n.parent == null || node.right!= null){ 5 return leftMostChild(node.right); 6 }else{ 7 8 TreeNode cur = node; 9 TreeNode parent = cur.parent; 10 // Go up until we’re on left instead of right 11 12 while(parent != null && parent.left != cur){ 13 cur = parent; 14 parent = parent.parent; 15 } 16 return parent; 17 } 18 } 19 public static TreeNode leftMostChild(TreeNode n) { 20 if(n == null) { 21 return null; 22 } 23 while(n.left!= null){ 24 n = n.left; 25 } 26 return n; 27 }
(2) 没有parent指针 http://www.geeksforgeeks.org/inorder-successor-in-binary-search-tree/
其实唯一不同的就是找parent或者gradparent那部分,这时候我们需要直到这棵树的root,从上向下遍历,记录parent
1 public TreeNode findSuccssor(TreeNode node, TreeNode root){ 2 3 if(node.right != null){ 4 return leftMostChild(node.right); 5 } 6 TreeNode succ = null; 7 //need to start from root, and search for successor down the tree 8 while(root != null){ 9 if(root.val < node.val){ 10 //node if on right subtree 11 12 root = root.right; 13 }else if(root.val > node.val){ 14 //node is on left subtree 15 succ = root; 16 root = root.left; 17 }else{ 18 //root.val == node.val; 19 break; 20 } 21 } 22 23 return succ; 24 }
时间: 2024-10-22 00:42:06