给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路:首先要搞清楚二叉树的中序遍历顺序为左子树->根节点->右子树。接下来要考虑该结点的位置,若该结点有右子树则查找右子树的最后一个左节点,若无左节点则返回该右结点;若该结点无右子树则查找其父节点,若该结点为父节点的左子树则返回该父结点,否则继续往上找。
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
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;
}
}