[8] offer prove safety. Next node binary tree

Title Description

Given a binary tree and one of the sites, how to find the next node in order traversal sequence? Tree nodes other two refer to the left and right child pointer, and a pointer pointing to a parent node

public class Node {
    int val;
    TreeLinkNode left = null;
    TreeLinkNode right = null;
    TreeLinkNode parent = null;

    Node(int val) {
        this.val = val;


  1. Have the right subtree when the next node in the right subtree of the left-most node
  2. No right subtree of time to find the parent node. The parent node of the current node left child? Yes, return to the parent node. Not, keep looking down on one parent parent, to determine whether the parent node is the left child of one parent, it returns the immediate parent node not then find ...
public class GetNextNode {
    public static class Node{
        int val;
        Node left;
        Node right;
        Node parent;

        public Node(int data){
            this.val = data;

    public Node getNextNode(Node node){
        if(node == null) return null;

        // 有右子树
        if(node.right != null){
            while(node.left != null){
                node = node.left;
            return node;

        // 没有右子树
        while(node.parent != null){
            if(node.parent.left == node) return node.parent;
            node = node.parent;
        return null;

  1. List item
Published 89 original articles · won praise 13 · views 20000 +

Guess you like

Origin blog.csdn.net/Dawn510/article/details/105259018