Relatively longer recursive C++ solution


  • 0
    S
    class Solution {
        public:
            int treeDepth(TreeNode* node, int& depth) {
                // return depth as soon as that is detected as the leaf node
                if (!node->left && !node->right)
                    return depth;
                
                int left_height = depth;
                int right_height = depth;
            
                if ( node->left && !node->right )
                    left_height = treeDepth(node->left, ++depth);
            
                else if ( !node->left && node->right )
                    right_height = treeDepth(node->right, ++depth);
            
                else
                {
                    int orig_depth = depth;
                    left_height = treeDepth(node->left, ++depth);
                    right_height = treeDepth(node->right, ++orig_depth);
                }
            
                return left_height > right_height ? left_height : right_height;
            }
    
            int maxDepth(TreeNode* root) {
                if (!root)
                    return 0;
                
                int depth = 1;
                return treeDepth(root, depth);
            }
    };

Log in to reply
 

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