LeetCode Balanced Binary Tree
2014-06-23 21:58
197 查看
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalanced(TreeNode *root) { int h; return dfs(root, h); } bool dfs(TreeNode* root, int& height) { height = 0; if (root == NULL) { return true; } int lh, rh; if (!dfs(root->left, lh)) return false; if (!dfs(root->right, rh)) return false; lh++, rh++; int diff = lh - rh; if (diff < -1 || diff > 1) return false; if (diff < 0) { height = rh; } else { height = lh; } return true; } };
第二轮:
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: bool valid; public: bool isBalanced(TreeNode *root) { valid = true; height(root); return valid; } int height(TreeNode* root) { if (!valid || root == NULL) { return 0; } int hl = height(root->left); int hr = height(root->right); int diff = max(hl, hr) - min(hl, hr); if (diff > 1) { valid = false; } return max(hl, hr) + 1; } };
再简化一下:
/** * 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: bool isBalanced(TreeNode* root) { return height(root) >= 0; } int height(TreeNode* root) { if (root == NULL) { return 0; } int lh = height(root->left); int rh = height(root->right); if (lh < 0 || rh < 0 || abs(lh - rh) > 1) { return -1; } return 1 + max(lh, rh); } };
相关文章推荐
- LeetCode 110 Balanced Binary Tree(平衡二叉树)(*)
- 开始刷题leetcode day3:Balanced Binary Tree
- Leetcode 树 Balanced Binary Tree
- 【LeetCode笔记】Balanced Binary Tree 高度平衡二叉树
- leetcode : Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- leetcode -day18 Balanced Binary Tree
- LeetCode110:Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode 110: Balanced Binary Tree
- Leetcode-标签为Tree 110. Balanced Binary Tree
- LeetCode刷题笔录Convert Sorted Array to Balanced Binary Search Tree
- LeetCode: Balanced Binary Tree 解题报告
- [LeetCode 110] - 平衡二叉树 (Balanced Binary Tree)
- leetcode Balanced Binary Tree
- 4.33 leetcode -33 balanced-binary-tree
- leetcode-110 Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- Balanced Binary Tree——LeetCode
- leetcode_110 Balanced Binary Tree