4.6

Topic 4.6 Write an algorithm to find the ‘next’ node (i.e.,in-order successor)of a given node in a binary search tree. You may assume that each node has a link to its parent.  

方法:

If n has a right subtree,

If n doesn’t have a right subtree, we are done traversing n’s subtree. We need to pick up where we left off with n’ parent, x. If n was to the left x, the next node should be x. (in-order). If n was to the right of x, we have fully traversed x’s subtree, go up, return x’s parent.

If we hit the rightmost, we should return null.

public class C4_6 {
	public static TreeNode inorderSucc(TreeNode n) { 
		if (n == null) return null;//情况3:到达最右,返回null
		
		//情况1:头结点,有右子树
		if (n.parent == null || n.right != null) { //注意,要考虑头结点的情况,n.parent==null
			return leftMostChild(n.right); //返回的是右子树的leftMostChild
		} else { 
			TreeNode q = n;
			TreeNode x = q.parent;//这两个都要存起来,因为向上的话,这两个都要更新
			while(x!=null && x.left!=n){//情况2.1 n无右子树,n遍历完;n是一个右子树,n的parent遍历完,向上,返回n的parent的parent.
				q = x;
				x = x.parent;
			}
			//情况2。2 n无右子树,n遍历完;n是一个左子树,返回n的parent
			    return x;
			}       
		}
	
	//该方法的思想就是一直找n.left直到n.left==null.
	public static TreeNode leftMostChild(TreeNode n) {
		if (n == null) {
			return null;
		}
		while (n.left != null) {
			n = n.left; 
		}
		return n; 
	}
	
	public static void main(String[] args) {
		int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		TreeNode root = TreeNode.createMinimalBST(array);
		System.out.println(inorderSucc(root).data+"\n"+inorderSucc(inorderSucc(root)).data);
	}
}
//结果
6
7



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值