[C++] [Java] Clean Code


  • 5

    C++

    class Solution {
    public:
        int diameterOfBinaryTree(TreeNode* root) {
            int diameter = 0;
            height(root, diameter);
            return diameter;
        }
    private:
        int height(TreeNode* node, int& diameter) {
            if (!node) {
                return 0;
            }
            int lh = height(node->left, diameter);
            int rh = height(node->right, diameter);
            diameter = max(diameter, lh + rh);
            return 1 + max(lh, rh);
        }
    };
    

    Java

    public class Solution {
        public int diameterOfBinaryTree(TreeNode root) {
            int[] diameter = new int[1];
            height(root, diameter);
            return diameter[0];        
        }
    
        private int height(TreeNode node, int[] diameter) {
            if (node == null) {
                return 0;
            }
            int lh = height(node.left, diameter);
            int rh = height(node.right, diameter);
            diameter[0] = Math.max(diameter[0], lh + rh);
            return 1 + Math.max(lh, rh);
        }
    }
    

  • 0
    F

    @alexander said in [C++] [Java] Clean Code:

    return 1 + max(lh, rh);
    what is the meaning


  • 0

    @followyounger height of parent = max(height of left child, height of right child) + 1;


Log in to reply
 

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