题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
1、思路分析
根据中序遍历的定义,如果当前遍历结点的右子树不为空,我们总是寻找其右子树的最左边的结点作为遍历的下一个结点;如果右子树为空,说明当前结点及其子树已经遍历完成,这时需要判断当前结点是其父结点的左孩子还是右孩子,如果是左孩子,下一个遍历的结点是其父结点,如果是右孩子,则需要找到其祖先中为左孩子的结点,再返回该左孩子结点的父结点。
2、代码

public class Solution {
    public TreeLinkNode GetNext(TreeLinkNode pNode) {
        if(pNode == null) return null;
        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;
            }
            pNode = pNode.next;
        }
        return null;
    }
}