Leetcode 110. Balanced Binary Tree (Easy) (cpp)

来源:互联网 发布:微信发假金额红包软件 编辑:程序博客网 时间:2024/06/06 20:00

Leetcode 110. Balanced Binary Tree (Easy) (cpp)

Tag: Tree, Depth-first Search

Difficulty: Easy


 class Solution { public: bool isBalanced(TreeNode* root) { if (!root) return true; else if (abs(depth(root->left) - depth(root->right)) > 1) return false; else return isBalanced(root->left) && isBalanced(root->right); } int depth(TreeNode* root) { if (!root) return 0; else if (!(root -> left) && !(root -> right)) return 1; int depth_L = depth(root -> left); int depth_R = depth(root -> right); return depth_L > depth_R ? depth_L + 1 : depth_R + 1; } };


0 0