Easy understood JAVAdfs+max solution with explanation


  • 0
    Y

    Use dfs() to go through every node of the tree, and use recur() to calculate the max diameter of the node. Use max to store the value of diameter.

    public class Solution {
        private int max;
        public int diameterOfBinaryTree(TreeNode root) {
            max = 0; 
            dfs(root);
            return max;
        }
        private int recur(TreeNode node) {
            if(node == null) return 0;
            return Math.max(recur(node.left),recur(node.right)) + 1;
        }
        private void dfs(TreeNode node) {
            if(node != null) {
                max = Math.max(max, recur(node.left) + recur(node.right));
            } else {
                return;
            }
            dfs(node.left);
            dfs(node.right);
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.