题目
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
知识点
二叉树
思路
解法一、按照中序遍历的顺序将每一个结点存入ArrayList,再遍历list找到当前结点的下一个结点,返回;代码略。
解法二、穷举所有条件;
主要分为1.有右子树 和2.无右子树两种情况:
- 有右子树时,找到右子树中的最左边的叶子结点返回;
- 没有右子树时,若没有父结点,则直接返回null;
- 没有右子树时,若有父结点,则一直向上走,直到此结点node是父结点nextNode的左子结点,返回node;
- 没有右子树时,若有父结点但node一直不是nextNode的左子结点(例如pNode是一棵树的最右叶子结点,是中序遍历的最后一个结点),则返回null。
代码
/*
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){
TreeLinkNode node = pNode.right;
while(node.left!=null) node = node.left;
return node;
}
else if(pNode.next!=null){
TreeLinkNode nextNode = pNode.next;
TreeLinkNode node = pNode;
while(node!=nextNode.left){
node = node.next;
nextNode = nextNode.next;
if(nextNode==null) return null;
}
return nextNode;
}
else return null;
}
}