题目,给一个二叉树的中序遍历序列,和某个结点,返回该结点的下一个结点值
输入:二叉树,某节点
输出:该节点的下一个结点
package offer_algorithms;
public class NextNodeForBT {
/**
* 给定一个二叉树和其中的一个结点,找出中序遍历序列的下一个结点
* 分情况:
* 若该节点时根结点,则下一个结点时其右孩子(该节点有左右孩子时,下一个结点为右孩子)
* 该节点没有右孩子,而且它还是其父节点的右孩子,逆向找回去,找到一个父节点a以及a的父节点b且a是b的左孩子时---b就是下一个结点
*/
class Node {
int data;
Node left;
Node right;
Node parent;
}
public Node getNext(Node t) {
if (t == null) {
return null;
}
Node nextNode = new Node();
if (t.right != null)//有右孩子
{
Node rNode = t.right;
while (rNode.left != null) {
rNode = rNode.left;
}
nextNode = rNode;
} else if (t.parent != null) {
Node current = t;
Node tParent = t.parent;
while (tParent != null && current == tParent.right) {
current = tParent;
tParent = tParent.parent;
}
nextNode = tParent;
}
return nextNode;
}
}