首页 > 其他 > 详细

Find下一个Node in BST

时间:2015-05-03 14:32:18      阅读:298      评论:0      收藏:0      [点我收藏+]

给定一个node,找inorder traversal 里下一个。

最直接的想法是inorder遍历整个bst,然后在遍历的结果中查找。但是这样耗费多余的空间和时间。

geeksforgeek

(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     }
View Code

 

 

 (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     }
View Code

 

Find下一个Node in BST

原文:http://www.cnblogs.com/xiaomaoliu/p/4473520.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!