Leetcode:balanced_binary_tree

来源:互联网 发布:xc系列编程工具 编辑:程序博客网 时间:2024/06/09 15:47

一、     题目

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


2 2
原创粉丝点击