Balanced Binary Tree
来源:互联网 发布:电路图仿真软件 编辑:程序博客网 时间:2024/06/05 20:19
还是深搜。判断左面子树合法吗?右面子树合法吗?左右子树的深度差合法吗?如果不合法,直接返回不合法;否则,返回合法,并且将深度置为左右子树深度大的那个加一。
/** * 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 depth; return dfs(root, depth); } bool dfs(TreeNode *root, int &depth) { if (root == NULL) { depth = 0; return true; } int l_depth, r_depth; bool l_valid, r_valid; l_valid = dfs(root->left, l_depth); r_valid = dfs(root->right, r_depth); if (!l_valid || !r_valid || max(l_depth, r_depth) - min(l_depth, r_depth) > 1) return false; depth = max(l_depth, r_depth) + 1; return true; }};
http://oj.leetcode.com/problems/balanced-binary-tree/
0 0
- 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
- Balanced Binary Tree
- Balanced Binary Tree
- 【leetcode】Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode]Balanced Binary Tree
- Balanced Binary Tree
- Balanced Binary Tree
- [LeetCode] Balanced Binary Tree
- [Leetcode]Balanced Binary Tree
- [leetcode]Balanced Binary Tree
- mybatis查询类型为int的字段,返回null的异常
- EJB-01:企业级开发背景知识
- 【线段树】单点更新4
- UINavigationController介绍
- EJB-02:EJB开发流程
- Balanced Binary Tree
- java 利用spring JavaMailSenderImpl发送邮件,支持普通文本、附件、html、velocity模板
- Android 4.22 与PC 单线程通信Socket
- 黑马程序员_银行业务调度系统
- Hibernate_QL
- 菜鸟学SSH(六)——Spring事务管理
- 认真练习一个小时,胜过三心二意三个小时
- 黑马程序员----java编程(3)
- EJB-03:SessionBean