110. Balanced Binary Tree
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.
判断二叉树是不是平衡二叉树
递归求左右子树的高度差,为了效率,在判断的过程中记录下子树的深度。
当左右子树都平衡时,再判断高度差。
代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isBalance(TreeNode* root, int &dep) { if (root == NULL) { dep = 0; return true; } int l ,r; int left = 0,right = 0; l = isBalance(root->left,left); r = isBalance(root->right,right); if (l && r) { dep = max(left, right) + 1; if (abs(left - right) <= 1) return true; return false; } else return false; } bool isBalanced(TreeNode* root) { int dep = 0; if (root == NULL) return true; if (isBalance(root, dep)) return true; return false; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号: