现在的位置: 首页 > 综合 > 正文

Leetcode:balanced_binary_tree

2019年11月04日 ⁄ 综合 ⁄ 共 612字 ⁄ 字号 评论关闭

一、     题目

   判断给定的二叉树是否是平衡二叉树,即每一个节点的深度相差不大于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;
	}
};

抱歉!评论已关闭.