剑指offer——查找二叉树的下一个节点


题目描述:

               给定一棵二叉树和其中的一个节点,如何找出中序遍历序列的下一个节点?数中的节点除了有两个分别指向     左、右节点的指针,还有一个指向父亲节点的指针。


       我们首先看一棵树:



对于求一棵二叉树中序遍历序列中一个节点的下一个节点一般会有3种情况

第一种情况: 节点有右子树,则下一节点就从它的右子树中查找
如图


第二种情况:没有右子节点,而且它还是其父节点的左子节点
如图:


第三种情况:节点既没有右子树,而且还是父亲节点的右子节点。
如图



相关代码如下:
package test;

class BinaryTreeNode {
	public int value;
	public BinaryTreeNode leftNode;;
	public BinaryTreeNode rightNode;
	public BinaryTreeNode parentNode;
	
	public BinaryTreeNode() {
		
	}
	
	public BinaryTreeNode(int value) {
		this.value = value;
		this.leftNode = null;
		this.rightNode = null;
		this.parentNode = null;
	}
	
}
public class GetNextTreeNode {
	
	public BinaryTreeNode getNext(BinaryTreeNode pNode) {
		BinaryTreeNode currentNode = null;
		
		//情况一:判断是否有右孩子,如果有右孩子
		if(pNode.rightNode != null) {
			currentNode = pNode.rightNode;
			while(currentNode.leftNode != null) {
				currentNode = currentNode.leftNode;
			}
			
			return currentNode;
		}
		
		//情况二:如果是其父节点的左孩子,其父节点就是pNode的下一个节点
		else if( pNode.parentNode != null && pNode.parentNode.leftNode == pNode) {
			return pNode.parentNode;
		}
		
		//情况三:如果pNode节点没有右子树,却其父亲节点,爷爷节点...
		//其下一节点就是使其  父亲节点... 处于左子树的最左孩子
		else {
			currentNode = pNode.parentNode;
			while(currentNode.parentNode != null) {//爷爷节点
				if(currentNode.parentNode.leftNode == currentNode) {//找出爷爷节点的最左子树
					return currentNode.parentNode;
				}
				currentNode = pNode.parentNode;
			}
		}
		
		return null;
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值