[Offer] [8] [next node in preorder]

Title Description

  Given a binary tree and a node of them, how to find the next node in order traversal order? In addition to the node in the tree are pointers to two child nodes other than the left and right, as well as a pointer pointing to the parent node.

Ideas analysis

  1. The chain structure has a pointer to the parent node, the method for the first input node of the binary tree
  2. Divided into two cases:
    • If the current node has a right subtree, a node traversal sequence which is the leftmost child node of its right sub-tree;
    • If the current node is not the right subtree:
      • The node is its parent node's left child node, then its next node i.e. its parent;
      • The node is the right child node of its parent node, then his next node on the need for search along its parent chain, to find if a node is its parent node's left child node ( reproducing the first case), so is the next node for this node 's parent node.

Java code

public static TreeNodeWithParent GetNext(TreeNodeWithParent tree) {
        return Solution1(tree);
    }

    /**
     * 
     * @param tree
     * @return
     */
    private static TreeNodeWithParent Solution1(TreeNodeWithParent tree) {
        if (tree == null) {
            return null;
        }
        TreeNodeWithParent p = tree;

        if (p.right != null) {
            p = p.right;
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
        while (p.parent != null) {
            if (p == p.parent.left) {
                return p.parent;
            }
            p = p.parent;
        }
        return null;
    }

Code link

Offer to prove safety codes -Java

Guess you like

Origin www.cnblogs.com/haoworld/p/offer8-zhong-xu-bian-li-de-xia-yi-ge-jie-dian.html