zoukankan      html  css  js  c++  java
  • BST平衡二叉树的后继结点(最近的大)

    public class InorderSuccessorInBST {//平衡二叉树查找后继结点
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            if (p == null) {
                return null;
            }
            if (getLastEntry(root) == p) {//根节点的最右边的节点是最后节点,是没有后继结点的。
                return null;
            }
            if (p.right != null) {//查找第一个右节点的最左边的节点。
                return getFirstEntry(p.right);
            }
            //p.right == null
            TreeNode parent = root;//只有left,right没有parent节点。
            TreeNode temp = root;
            while (parent != null) {
                if (parent == p) {
                    break;
                } else if (p.val < parent.val) {//左边走的时候,twmp指向父节点,parent指向子节点。挨着走。
                    temp = parent;
                    parent = parent.left;
                } else {//右边走的时候,temp不变,
                    parent = parent.right;
                }
            }
            return temp;
        }
    
        private TreeNode getLastEntry(TreeNode p) {
            while (p.right != null) {
                p = p.right;
            }
            return p;
        }
    
        private TreeNode getFirstEntry(TreeNode p) {
            while (p.left != null) {
                p = p.left;
            }
            return p;
        }
    }
  • 相关阅读:
    将数据导入PostGIS
    图层管理
    CentIOS PHP 扩展库
    js 笔记 数组(对象)
    JSP 中的 Request 和 Response 对象
    ubuntu 安装 LAMP
    html 学习笔记
    Struts Ajax Json
    Servlet 笔记
    PHP+MYSQL 出现乱码的解决方法
  • 原文地址:https://www.cnblogs.com/yaowen/p/11118872.html
Copyright © 2011-2022 走看看