剑指offer第二版-8.二叉树的下一个节点

描述:给定一棵二叉树和其中的一个节点,找出中序遍历序列的下一个节点。树中应定义指向左节点、右节点、父节点的三个变量。

思路:

1.如果输入的当前节点有右孩子,则它的下一个节点即为该右孩子为根节点的子树的最左边的节点,比如2->5,1->3

2.如果输入的当前节点没有右孩子,就需要判断其与自身父节点的关系:

  2.1如果当前节点没有父节点,那所求的下一个节点不存在,返回null.

  2.2如果输入节点是他父节点的左孩子,那他的父节点就是所求的下一个节点,比如4->2

  2.3如果输入节点是他父节点的右孩子,那就需要将输入节点的父节点作为新的当前节点,返回到2.1,判断新的当前节点与他自身父节点的关系,比如5->1

考点:对中序遍历的理解。

树节点结构

/**
 * Copyright(C) 2019 Hangzhou Differsoft Co., Ltd. All rights reserved.
 *
 */
package com.java.offer.tree;

/**
 * @since 2019年2月19日 下午5:30:18
 * @author xuchao
 * 
 *  带有父指针的二叉树节点
 */
public class TreeNode2 {

    public int val;
    public TreeNode2 left;
    public TreeNode2 right;
    public TreeNode2 father;
    
    public TreeNode2(int val) {
        this.val = val;
        this.left = null;
        this.right = null;
        this.father = null;
    }
}

代码:

/**
 * Copyright(C) 2019 Hangzhou Differsoft Co., Ltd. All rights reserved.
 *
 */
package com.java.offer;

import com.java.offer.tree.TreeNode2;

/**
 * @since 2019年2月19日 下午5:35:39
 * @author xuchao 
 * 
 * 二叉树的下一个节点
 */
public class P8_NextNodeInBinaryTrees {
    
    public static TreeNode2 getNext(TreeNode2 node) {
        if (node == null) {
            return null;
        }
        if(node.right!=null) {
            node = node.right;
            while (node.left != null) {
                node = node.left;
            }
            return node;
        } else if (node.father != null) {
            if (node.father.left == node) {
                return node.father;
            }
            if (node.father.father != null) {
                return node.father.father;
            }
        }
        return null;
    }
    
    //         1
    //       // \\
    //      2     3
    //    // \\
    //   4     5
    // inorder->42513
    public static void main(String[] args) {
        TreeNode2 root = new TreeNode2(1);
        root.left = new TreeNode2(2);
        root.left.father = root;
        root.right = new TreeNode2(3);
        root.right.father = root;
        root.left.left = new TreeNode2(4);
        root.left.left.father = root.left;
        root.left.right = new TreeNode2(5);
        root.left.right.father = root.left;

        System.out.println(getNext(root.left.left).val);
        System.out.println(getNext(root.left).val);
        System.out.println(getNext(root.left.right).val);
        System.out.println(getNext(root).val);
        System.out.println(getNext(root.right));
    }
}

 

posted @ 2019-02-19 18:17  思丿无邪  阅读(142)  评论(0编辑  收藏  举报