题目 : 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
思路 :
(1)若该节点存在右子树:则下一个节点为右子树最左子节点(如图节点B)
(2)若该节点不存在右子树:这时分两种情况:
case1,该节点为父节点的左子节点,则下一个节点为其父节点(如图节点D)
case2,该节点为父节点的右子节点,则沿着父节点向上遍历,知道找到一个节点的父节点的左子节点为该节点,则该节点的父节点下一个节点(如图节点I,沿着父节点一直向上查找找到B(B为其父节点的左子节点),则B的父节点A为下一个节点)。
import java.util.Arrays;
public class Solution {
public TreeLinkNode getNext(TreeLinkNode pNode) {
if (pNode == null) {
return pNode;
}
if (pNode.right != null) {
// 节点有右子树
pNode = pNode.right;
while (pNode.left != null) {
pNode = pNode.left;
}
return pNode;
} else if (pNode.next != null && pNode.next.left == pNode) {
// 节点无右子树,且该节点为父节点的左子节点
return pNode.next;
} else if (pNode.next != null && pNode.next.right == pNode) {
// 节点无右子树且该节点为父节点的右子节点
while (pNode.next != null && pNode.next.left != pNode) {
pNode = pNode.next;
}
return pNode.next;
} else {
// 节点无父节点,即节点为根结点
return pNode.next;
}
}
}
class TreeLinkNode {
int value = 0;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
public TreeLinkNode(int value) {
this.value = value;
}
// 为了显示方法,我们重新toString
@Override
public String toString() {
return "TreeLinkNode [value=" + value + "]";
}
}