题目描述:
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
题目分析:
注意题目没有给出二叉树的根节点
分情况进行讨论:
- 如果给定的这个节点没有右孩子,则中序遍历的下一个节点就是该树的根节点,主要是根据父亲指针进行求根节点
该种情况下需要考虑两种特殊情况: 第一:如果所给定的节点是根节点,则直接进行返回null。第二:如果所给定的节点是整棵树的最右边的节点,那么也返回空 - 如果给定的这个节点有右子树,那么他的中序遍历的下一个节点就是他的右子树的最左边的节点
递归版本:
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode.right == null){
if(pNode.next == null) return null;
if (pNode == pNode.next.left) return pNode.next;
else if (pNode == pNode.next.right){
TreeLinkNode root = GetRootnode(pNode);
if (pNode == GetRightnode(root)) return null;
else return root;
}
}
return GetLeftnode(pNode.right);
//return pNode;
}
//获取一棵数的最左边的节点
public TreeLinkNode GetLeftnode(TreeLinkNode pNode){
if (pNode.left == null) return pNode;
return GetLeftnode(pNode.left);
}
//获取一棵数的最右边的节点
public TreeLinkNode GetRightnode(TreeLinkNode pNode){
if (pNode.right == null) return pNode;
return GetRightnode(pNode.right);
}
//获取一棵树的根节点
public TreeLinkNode GetRootnode(TreeLinkNode pNode){
if (pNode.next == null) return pNode;
return GetRootnode(pNode.next);
}
}
非递归版本(参考):
作者:skoy12
链接:https://www.nowcoder.com/questionTerminal/9023a0c988684a53960365b889ceaf5e?f=discussion
来源:牛客网
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
if(pNode == null) return null;
TreeLinkNode res;
if(pNode.right == null){
res = pNode;
while(res.next != null && res.next.right == res){
res = res.next;
}
return res.next;
}
res = pNode.right;
while(res.left != null){
res = res.left;
}
return res;
}