带parent指针的successor求解

时间:2023-11-17 10:12:14

题目:

  给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点(不存在重复数据)。树中的结点不仅包含左右子结点,同时包含指向父结点的指针。

    带parent指针的successor求解

思路:

  如果当前节点有右孩子,则下一个节点是右孩子中最左子节点。如果当前节点是其父节点的左子节点,则下一个节点就是父节点(节点没有右孩子)。如果当前节点是父节点的右子节点(节点没有右孩子),下一个节点:父节点是其父节点的左孩子。最后没找到的话 就说明这是最后一个,不存在他的下一个了。

代码:

/*有parent的解法*/
public class Successor0 {
public TreeNode<Integer> findSuccessor(TreeNode<Integer> node) {
if (node == null)
return null;
if (null != node.right) {
return minOfRight(node.right);
} else {
TreeNode<Integer> p = node;
while (p.parent != null && p == p.parent.right) {
p = p.parent;
}
return p.parent;
}
} private TreeNode<Integer> minOfRight(TreeNode<Integer> right) {
TreeNode<Integer> p = right;
while (p.left != null)
p = p.left;
return p;
} public static class TreeNode<T> { public T val;
public TreeNode<T> left = null;
public TreeNode<T> right = null;
public TreeNode<T> parent = null; public TreeNode(T val) {
this.val = val;
} }
}