leetcode - Balanced Binary Tree
2014-06-18 21:36
330 查看
题目:Balanced Binary Tree
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.
个人思路:
1、判断每个节点(子树)的高度差,高度差在绝对值为1的范围内便是平衡二叉树
2、可以适当改造计算树高度的方法,即树的高度为左子树与右子树高度较大者加1
代码:
View Code
上网搜了一些帖子,方法都是类似,就不贴出来了
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.
个人思路:
1、判断每个节点(子树)的高度差,高度差在绝对值为1的范围内便是平衡二叉树
2、可以适当改造计算树高度的方法,即树的高度为左子树与右子树高度较大者加1
代码:
#include <stddef.h> #include <iostream> /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: bool isBalanced(TreeNode *root) { balanced = true; getDepth(root); return balanced; } int getDepth(TreeNode *root) { if (root == NULL) { return 0; } int leftDepth = getDepth(root->left); int rightDepth = getDepth(root->right); if (leftDepth - rightDepth > 1 || leftDepth - rightDepth < -1) { balanced = false; } return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1; } private: bool balanced; }; int main() { TreeNode *root = new TreeNode(1); root->right = new TreeNode(1); root->right->right = new TreeNode(1); Solution s; s.isBalanced(root); std::cout << root->val << std::endl << root->right->val << std::endl << root->right->val << std::endl; system("pause"); return 0; }
View Code
上网搜了一些帖子,方法都是类似,就不贴出来了
相关文章推荐
- Leetcode Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree (平衡二叉树)
- 【Leetcode】110. Balanced Binary Tree 【DFS】
- leetcode第一刷_Balanced Binary Tree
- Leetcode[110]-Balanced Binary Tree
- leetcode No110. Balanced Binary Tree
- leetcode_c++:树:Balanced Binary Tree(110)
- Balanced Binary Tree——LeetCode
- [LeetCode] 110. Balanced Binary Tree
- LeetCode:110_Balanced Binary Tree | 平衡二叉树 | Easy
- leetcode — balanced-binary-tree
- [LeetCode]Balanced Binary Tree
- leetcode Balanced Binary Tree 后序遍历思想避免重复遍历结点
- LeetCode Balanced Binary Tree
- Leetcode:balanced_binary_tree
- Leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Leetcode: Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree