• 寻找二叉树最远的叶子结点


    面试的时候碰到一个题:如何找到一个二叉树最远的叶子结点,以及这个叶子结点到根节点的距离?

    第一反应肯定是递归

    如何能找到最远的叶子结点,同时也能记下这个叶子节点到根节点的距离呢?采用一个List保持从根节点到叶子节点的路径就可以了,这个list的长度-1就是叶子结点到根节点的距离,list的最后一个结点就是到叶子结点

    二叉树我就不用设计了,具体代码参见我的另一篇文章

     1     /**
     2      * 寻找最远的叶子节点
     3      */
     4     public void findFarestLeaf() {
     5         List<Node> path = new ArrayList<Node>();
     6         List<Node> longestPath = findLongestPath(root, path);
     7         Node leaf = longestPath.get(longestPath.size() - 1);
     8         System.out.println("最远的叶子节点是<" + leaf.key + ", " + leaf.value + ">,到根节点的距离是:"+(longestPath.size() - 1));
     9     }
    10 
    11     public List<Node> findLongestPath(Node x, List<Node> path) {
    12         if (x == null)
    13             return path;
    14         // 每次递归必须新建list,要不然会导致递归分支都在同一个list上面做,实际是把所有结点都加入这个list了
    15         List<Node> currPath = new ArrayList<Node>();
    16         currPath.addAll(path);
    17         currPath.add(x);
    18         List<Node> leftPath = findLongestPath(x.left, currPath);
    19         List<Node> rightPath = findLongestPath(x.right, currPath);
    20         if (leftPath.size() > rightPath.size())
    21             return leftPath;
    22         else
    23             return rightPath;
    24     }
  • 相关阅读:
    [luogu p4447] [AHOI2018初中组]分组
    咕咕咕通知
    [luogu p3817] 小A的糖果
    [luogu p1228] 地毯填补问题
    [luogu p1259] 黑白棋子的移动
    [luogu p3612] [USACO17JAN]Secret Cow Code S
    [luogu p1990] 覆盖墙壁
    [luogu p1928] 外星密码
    [luogu p2036] Perket
    [luogu p2392] kkksc03考前临时抱佛脚
  • 原文地址:https://www.cnblogs.com/evasean/p/7999902.html
Copyright © 2020-2023  润新知