找出"中序遍历"时二叉树的下一个节点
解题思路
中序遍历即是"左根右"的顺序遍历,考虑几种情况
- 如果当前节点有右子树, 则下一节点为右子树的最左的节点
- 如果当前节点没有右子树
- 且没有父节点,则该节点已是中序遍历的最后节点
- 有父节点
- 且是父节点的左子节点,则该父节点是遍历的下一个节点
- 且是父节点的右子节点,则需要往上找到第一个
是它父节点的左子节点的节点
,并返回父节点有可能往上找到一个没有父节点的节点,此时中序遍历也已结束
代码
class Node {
Node parent;
Node left;
Node right;
int value;
public Node(int value) {
this.value = value;
}
}
public Node getNextOfInorder(Node node) {
if (node == null) {
return null;
}
Node cur = node;
// 如果当前节点有右子树, 则下一节点为右子树的最左的节点
if (cur.right != null) {
cur = cur.right;
while (cur.left != null) {
cur = cur.left;
}
return cur;
}
// 如果当前节点没有右子树
// 并且父节点为空, 则该节点为最后一个节点
if (cur.parent == null) {
return null;
}
// 如果当前节点没有右子树
// 则需要往上找到第一个是它父节点的左子节点的节点, 返回父节点
while (cur.parent != null && cur != cur.parent.left) {
cur = cur.parent;
}
return cur.parent;
}