zoukankan      html  css  js  c++  java
  • 二叉树的下一个节点(给定一棵二叉树的其中一个节点,请找出中序遍历序列的下一个节点)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode father;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
    
        /**
         * 获取二叉树中序遍历结点的下一个结点
         *
         * @param p 某结点
         * @return p的下一个结点
         */
        public TreeNode inorderSuccessor(TreeNode p) {
            if (p == null) {
                return null;
            }
    
            TreeNode cur = p.right;
    
            // 右子树不为空
            if (cur != null) {
                while (cur.left != null) {
                    cur = cur.left;
                }
                return cur;
            }
    
            // 右子树为空
            TreeNode father = p.father;
            while (father != null && father.left != p) {
                p = father;
                father = p.father;
            }
            return father;
        }
    }

    分析一下如果是父节点的右节点,为什么要这样找下一分

    有以下几种情况 一

     情况二

     所以要通过遍历找出 该节点的父节点的左节点是否等于该节点。

    即结束条件是循环 father.left == p

  • 相关阅读:
    Python 线程池,进程池,协程,和其他
    python 类的特殊成员方法
    Python 进程,线程,协程
    Python Socket第二篇(socketserver)
    Python 面向对象
    Python Socket
    saltstack 基础
    Python 面向对象学习
    Python 常用模块
    日志滚动工具
  • 原文地址:https://www.cnblogs.com/laolei11/p/11881427.html
Copyright © 2011-2022 走看看