zoukankan      html  css  js  c++  java
  • 给出一个二叉树的节点,返回该节点的后继节点


    /**
    * 给出一个二叉树的节点,返回该节点的后继节点(中序遍历的下一个节点称为后继节点)
    * <p>
    * 1)如果该节点有右子树,那么该节点的后继节点一定是右子树上最左边的节点;
    * 2)如果该节点无右子树,那么往上找;
    * 3)如果该节点是父节点的左子树,那么返回该父节点;如果该节点是父节点的右子树,继续上找
    * 4)重复3)直到找到该节点或找到根节点的父节点为null
    */
    public class SuccessorNode {

    public static Node getSuccessorNode(Node node) {
    if (node == null) {
    return null;
    }
    if (node.right != null) {
    return getMostLeft(node.right);
    }
    Node parent = node.parent;
    while (parent != null && parent.right == node) {
    node = parent;
    parent = node.parent;
    }
    return parent;
    }

    private static Node getMostLeft(Node node) {
    if (node == null) {
    return null;
    }
    while (node.left != null) {
    node = node.left;
    }
    return node;
    }

    /**
    * 二叉树结构
    */
    public static class Node {

    public int value;

    public Node left;

    public Node right;

    public Node parent;

    public Node(int value) {
    this.value = value;
    }

    }

    }

    /* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
  • 相关阅读:
    python安装cnstd卡住
    _、__、__xx__之间的差别
    Celery模块使用
    同一主机,开启多个不同端口的redis进程
    php配置变更记录
    Linux安装Nodejs
    ElasticSearch中term和match探索
    Centos安装elasticsearch,php连接使用
    centos8自定义目录安装php7.3
    centos8自定义目录安装nginx
  • 原文地址:https://www.cnblogs.com/laydown/p/12950403.html
Copyright © 2011-2022 走看看