题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
核心代码实现
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
//举例:某二叉树的中序序列为{D,B,H,E,I,A,F,C,G},前序序列为{A,B,D,E,H,I,C,F,G}
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode){
if(pNode == null){
return null;
}
//若当前节点的右子树非空,则返回其右子树的最左节点,如B-H,A-F
if(pNode.right != null){
pNode = pNode.right;
while(pNode.left != null){
pNode = pNode.left;
}
return pNode;
}
//若当前节点的父节点非空,则返回其父节点作为左子树的对应父节点
while(pNode.next != null){
if(pNode.next.left == pNode){
return pNode.next; //如D-B,H-E,F-C
}
pNode = pNode.next; //如E-I,I-A,C-G
}
return null;
}
}