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中最长的一端优势,这是这道题的特色

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

猜你喜欢

转载自www.cnblogs.com/immiao0319/p/12962932.html