zoukankan      html  css  js  c++  java
  • 543. Diameter of Binary Tree 543.二叉树直径

    Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

    Example:
    Given a binary tree

              1
             / 
            2   3
           /      
          4   5    
    

     

    Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

    return helper(root.left) + helper(root.right);
    我想的是:在主函数中调用递归
    我去。。和正确答案的分歧好严重。。
    首先,这种【计算题】还是用DC为主。DC需要在helper函数内部,主函数就一个调用就行了。

    怎么保证是最长路径呢?就直接左右递归就行了吧我觉得。比较得用max
    max是全局变量、维持结果return left right中最长的一端优势,这是这道题的特色

    还是原来的traverse相加的思路,就是不记得用DC了
    做了2遍还是对思路毫无印象啊,得彻彻底底理解才能记住

    class Solution {
        int max = 0;
        
        public int diameterOfBinaryTree(TreeNode root) {
            //cc
            if (root == null) 
                return 0;
            
            getLength(root);
            
            return max;
        }
        
        int getLength(TreeNode root) {
            //cc
            if (root == null) 
                return 0;
            
            int left = getLength(root.left);
            int right = getLength(root.right);
            
            max = Math.max(max, left + right);
            
            return Math.max(left, right) + 1;
        }
    }
    View Code
  • 相关阅读:
    Alpha 冲刺 (7/10)
    Alpha 冲刺 (6/10)
    同学录
    Alpha 冲刺 (5/10)
    Letcode刷题总结知识点
    python 基础语法
    Python 文件读写与编码解读
    py2exe界面和程序开发打包
    求职者五险一金解读
    互联网企业程序题总结
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12962932.html
Copyright © 2011-2022 走看看