LeetCode 543 Diameter of Binary Tree

The diameter of a binary tree is the length of the longest path between any two nodes in a tree.

so it’s actually needs us to get the longest path in the binary tree, no matter it surpass the root or not.

return the length of that path.

diameter(root) = Math.max(longestPath(root),longestPath(other nodes)) //this actually means that we need to maintain a global maximal
longestPath(root) means the longest path across the root, so longestpath(root.left) + longestPath(root.right) + 1;
So I’m implement my idea: (check every node and calculate the longest path passing through this node) but it’s just wrong

class Solution {
    
    public int diameterOfBinaryTree(TreeNode root) {
        int max = 0;
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            max = Math.max(max, longestPath(cur));
            if (cur.left != null) stack.push(cur.left);
            if (cur.right != null) stack.push(cur.right);
        }
        return max;
    }
    
    private int longestPath(TreeNode root) {
        if (root == null) return 0;
        return longestPath(root.left) + longestPath(root.right) + 1;
    }
}

but the correct answer, I just can’t really understand them…even though it looks tidy and simple.

class Solution {
    
    private int max;
    
    public int diameterOfBinaryTree(TreeNode root) {
        
        maxDepth(root);
        return max;
    }
    
    private int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int left = maxDepth(root.left); //get the maxDepth passing curent node(not necessaily as the root)
        int right = maxDepth(root.right); //
        max = Math.max(max, left + right); 
        return Math.max(left, right) + 1;
    }
    

}
posted @ 2020-11-16 11:44  EvanMeetTheWorld  阅读(11)  评论(0)    收藏  举报