Monday, August 28, 2017

543. Diameter of Binary Tree

https://leetcode.com/problems/diameter-of-binary-tree/description/
Solution 1. (9 ms)
    int maxDepth(TreeNode* node, int &mxDia) {
        if(!node) return 0;
        int dl = 0;
        if(node->left) {
            dl = maxDepth(node->left, mxDia) + 1;
        }
        int dr = 0;
        if(node->right) {
            dr = maxDepth(node->right, mxDia) + 1;
        }
        mxDia = max(dl + dr, mxDia);
        return max(dl, dr);
    }
    int diameterOfBinaryTree(TreeNode* root) {
        int mxDia = 0;
        maxDepth(root, mxDia);
        return mxDia;
    }
Solution 2. Similar to 1 (12 ms)
    int maxDepth(TreeNode* node, int &mxDia) {
        if(!node) return 0;
        int dl = maxDepth(node->left, mxDia);
        int dr = maxDepth(node->right, mxDia);
        mxDia = max(dl + dr, mxDia);
        return max(dl, dr) + 1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        int mxDia = 0;
        maxDepth(root, mxDia);
        return mxDia;
    }
Solution 3. (19 ms)
    int depth(TreeNode* node) {
        if(!node) return 0;
        return max(depth(node->left), depth(node->right)) + 1;
    }
    int diameterOfBinaryTree(TreeNode* root) {
        if(!root) return 0;
        int dia = depth(root->left) + depth(root->right);
        return max(dia, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right)));
    }

No comments:

Post a Comment