Cracking the coding interview--Q4.5

题目

原文:

Write an algorithm to find the ‘next’ node (e.g., in-order successor) of a given node in a binary search tree where each node has a link to its parent.

译文:

给定一个二叉查找树的结点,写一个算法去找“next”结点(即中序遍历后的后继结点),其中每一个结点都有指向其父亲的链接。

解答

题目要求的就是寻找中序遍历的后继结点。若该结点有右子树,则后继结点是其右子树的最左孩子;若该结点没有右子树,则需要不断地向上查找该结点的祖先, 直到找到第一个比它大的结点为止。

代码如下:

class Q4_5{
	public static TreeNode successor(TreeNode tnode){
		if(tnode==null) return null;
		if(tnode.rchild!=null){
			TreeNode tn=tnode.rchild;
			while(tn.lchild!=null){
				tn=tn.lchild;
			}
			return tn;
		}else{
			TreeNode p=tnode.parent;
			while(p!=null&&p.rchild==tnode){
				tnode=p;
				p=p.parent;
			}
			return p;
		}
	}
	public static void main(String[] args){
		int[]  arr={2,1,9,8,7,10};
		TreeNode root = TreeNode.createBinaryTree(arr);
		TreeNode t = root.rchild.lchild;
		TreeNode n= successor(t);
		System.out.println(n.value);
	}
}

class TreeNode{
	int value;
	TreeNode lchild;
	TreeNode rchild;
	TreeNode parent;
	
	public static void insert(TreeNode tnode,int x,TreeNode p){
		if(tnode==null){
			tnode=new TreeNode();
			tnode.value=x;
			tnode.lchild=null;
			tnode.rchild=null;
			if(p.value>x)
				p.lchild=tnode;
			else
				p.rchild=tnode;
			tnode.parent=p;
			return;
		}
		
		if(x<tnode.value){
			insert(tnode.lchild,x,tnode);
		}else{
			insert(tnode.rchild,x,tnode);
		}
	}
	
	public static TreeNode createBinaryTree(int[] values){
		TreeNode root=new TreeNode();
		root.value=values[0];
		for(int i=1;i<values.length;i++){
			insert(root,values[i],root);
		}
		return root;
	}
}

---EOF---

你可能感兴趣的:(Cracking the coding interview--Q4.5)