设为首页 加入收藏

TOP

Leetcode:balanced_binary_tree
2015-07-20 17:31:26 来源: 作者: 【 】 浏览:2
Tags:Leetcode:balanced_binary_tree

一、 题目

判断给定的二叉树是否是平衡二叉树,即每一个节点的深度相差不大于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) 
	{
		if(depthcheck(root)==0)
			return true;
		if(abs(depthcheck(root->left)-depthcheck(root->right))>1)
			return false;
		else
			return isBalanced(root->left) && isBalanced(root->right);
	}
 
	int depthcheck(TreeNode *root)
	{
		if(!root)
			return 0;
		int depthL=depthcheck(root->left)+1;
		int depthR=depthcheck(root->right)+1;
		return depthL > depthR ? depthL : depthR;
	}
};


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Palindrome Partitioning I,II[le.. 下一篇ZOJ 3471 Most Powerful(状压DP)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·在 Redis 中如何查看 (2025-12-26 03:19:03)
·Redis在实际应用中, (2025-12-26 03:19:01)
·Redis配置中`require (2025-12-26 03:18:58)
·Asus Armoury Crate (2025-12-26 02:52:33)
·WindowsFX (LinuxFX) (2025-12-26 02:52:30)