题目描述
思路:首先知道中序遍历的规则是:左根右,然后作图
结合图,我们可发现分成两大类:1、有右子树的,那么下个结点就是右子树最左边的点;(eg:D,B,E,A,C,G) 2、没有右子树的,也可以分成两类,a)是父节点左孩子(eg:N,I,L) ,那么父节点就是下一个节点 ; b)是父节点的右孩子(eg:H,J,K,M)找他的父节点的父节点的父节点...直到当前结点是其父节点的左孩子位置。如果没有eg:M,那么他就是尾节点。
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){//没有右子树的节点 只要下个节点不是null就向上判断父节点知道当前节点是父节点的第一个左节点
if(pNode.next.left == pNode){//
return pNode.next;
}
pNode = pNode.next;
}
return null;
}
}