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
  • 相关阅读:
    剑指offer51-正则表达式匹配
    剑指offer50-构建乘积数组
    剑指offer49-数组中的重复
    PHP系列笔记——Zend_Controller工作流程
    多态与重载
    读取文件数据的大概流程
    基于HTTP协议下载文件的实现
    C++中的面向对象笔记
    firebreath注册接口
    python读取excelxlsx,写入excel
  • 原文地址:https://www.cnblogs.com/immiao0319/p/12962932.html
Copyright © 2011-2022 走看看