LeetCode OJ - Balanced Binary Tree
来源:互联网 发布:淘宝上的尼康典范店 编辑:程序博客网 时间:2024/06/06 11:43
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.
分析:由Maximum Depth of Binary Tree 题目改进, 自底向上/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution { int ret;public: bool isBalanced(TreeNode *root) { if(root == NULL) return true; ret = true; DFS(root); return ret; } int DFS(TreeNode *root) { if(!ret) return 0; if(!root->left && !root->right) { return 1; } int ldepth = 0; int rdepth = 0; if(root->left) { ldepth = DFS(root->left); } if(root->right) { rdepth = DFS(root->right); } if(ldepth != rdepth + 1 && ldepth != rdepth - 1 && ldepth != rdepth) { ret = false; } return max(ldepth, rdepth) + 1; } };
改进如下:
/** * 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 dep = 0; return check(root, dep); } bool check(TreeNode *root, int &dep) { if(!root) { dep = 0; return true; } int leftDep, rightDep; if(!check(root->left, leftDep)) return false; if(!check(root->right, rightDep)) return false; dep = max(leftDep, rightDep) + 1; return abs(leftDep - rightDep) <= 1; }};
0 0
- LeetCode OJ:Balanced Binary Tree
- LeetCode OJ - Balanced Binary Tree
- [LeetCode OJ]Balanced Binary Tree
- LeetCode OJ Balanced Binary Tree
- <LeetCode OJ> 110. Balanced Binary Tree
- LeetCode OJ(110. Balanced Binary Tree)
- LeetCode: Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [Leetcode] Balanced Binary Tree
- LeetCode : Balanced Binary Tree
- LeetCode Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- android framework框架分析
- 更新到win8.1后vs2013打开出错的问题解决办法
- POJ题目分类
- 个性化IAAS还是通用型PAAS
- Tokyo Tyrant(TTServer)系列(二)-启动参数和配置
- LeetCode OJ - Balanced Binary Tree
- hadoop异常:hdfs.server.datanode.DataNode: Problem connecting to server: localhost/127.0.0.1:8020
- 便利的开发工具 CppUnit 快速使用指南
- 答读者问(7):有关实习、毕业论文及软件开发和测试的关系等问题
- 持续集成学习记录
- R语言备忘
- java_动态代理
- ARC深入浅出
- java设计模式-单例设计模式