Why my solution didn't work


  • 0
    L
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int getDepth(TreeNode* root)
        {
            if(root == NULL)
    		return 0;
        	int leftD = getDepth(root->left);
        	int rightD = getDepth(root->right);
        	return leftD > rightD ? (leftD + 1) : (rightD + 1);
        }
    
        int diameterOfBinaryTree(TreeNode* root) {
            if(root == NULL) return 0;
            return getDepth(root->left) + getDepth(root->right);
        }
    };
    

  • 0

    See here, case 2.
    Your code assume the longest path will include the root node. If not, it tells wrong answer.


Log in to reply
 

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