题目链接
算法思路
这题并不是简单地考查中序遍历,而是在理解中序遍历的基础上,明白下一个结点的位置。
二叉树的下一个结点分两种情况
-
有右结点的情况
如果存在右结点,那么下一个结点必定是这个右孩子的最左结点
-
无右结点的情况
如果没有右节点,那么必须向上找第一个左节点指向的树包含该结点的祖先结点
代码实现
/*
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.right!=null){
pNode = pNode.right;
while(pNode.left!=null){
pNode = pNode.left;
}
return pNode;
}else{
while(pNode.next!=null){
TreeLinkNode parent = pNode.next;
if(parent.left == pNode){
return parent;
}
pNode = pNode.next;
}
}
return null;
}
}