zoukankan      html  css  js  c++  java
  • 求二叉树距离最远的节点的最大距离

    求二叉树高度的变形,最大距离是两个子树的高度(定义一个空节点高度为-1,一个左右子树都为空的节点高度为0)
    之和+2 或者就是子问题左子树的max distance 或者是右子树的maxdistance。
    实际处理时只需要有一个全局变量,记录下当前的maxdistance,利用后序遍历,当访问根节点时,左右子树的中较大的max distance已经记录
    在该全局变量中,如果 left depth  + right depth + 2 > max distance 更新 max distance
            int MaxDistance() {
                int maxlen = 0;
                find(this->m_root, maxlen);
                return maxlen;
            }
            int find(T *root, int &maxlen) {
                int ldepth, rdepth;
                if (root->left())
                    ldepth = find(root->left(), maxlen);
                else
                    ldepth = -1;
                if (root->right())
                    rdepth = find(root->right(), maxlen);
                else
                    rdepth = -1;
                int depth;
                if (ldepth > rdepth)
                    depth = ldepth + 1;
                else
                    depth = rdepth + 1;
                if ((ldepth + rdepth + 2) > maxlen)
                    maxlen = ldepth + rdepth + 2;
                return depth;
            }

    allen:~/study/data_structure/calculator$ ./test_max_diatance
    1 -1 2 3 4 5 -1 -1 -1 -1 6 7 -1 8 -1 -1 9 -1 -1
      1

                              2

                  3                       6

            4                       7           9

         5                             8
    The max distance is 6


  • 相关阅读:
    解决问题:Jenkins Web 部署任务失败
    微信开发者调试工具官方下载地址
    Android机USB调试功能
    DOMContentLoaded 和 Load 和 Finish
    Json to string, string to Json
    static 和 new对象的区别
    c# Image/Pdf 预览
    在console 中执行异步方法
    c# 压缩zip
    js -- string 转 html
  • 原文地址:https://www.cnblogs.com/rocketfan/p/1552405.html
Copyright © 2011-2022 走看看