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.

 

思想:递归

  1. public int height(TreeNode root) {
  2. if(root==null) return 0;
  3. if(root.left == null && root.right == null) return 1;
  4. return Math.max(height(root.left),height(root.right))+1;
  5. }
  6. public boolean isBalanced(TreeNode root) {
  7. if(root==null) return true;
  8. if(root.left == null && root.right == null) return true;
  9. if(isBalanced(root.right) == false || isBalanced(root.left) == false) {
  10. return false;
  11. }
  12. if(Math.abs(height(root.left) - height(root.right))<=1) {
  13. return true;
  14. } else {
  15. return false;
  16. }
  17. }

改进:仅遍历一次节点

  1. bool isBalanced(TreeNode *root,int &height) {
  2. if(root==NULL) {
  3. height = 0;
  4. return true;
  5. }
  6. int left = 0;
  7. int lflag = isBalanced(root->left,left);
  8. int right = 0;
  9. int rflag = isBalanced(root->right,right);
  10. if(lflag&&rflag) {
  11. if(abs(left-right)<=1) {
  12. height = max(left,right) + 1;
  13. return true;
  14. }
  15. return false;
  16. }
  17. return false;
  18. }
  19. bool isBalanced(TreeNode *root) {
  20. int height=0;
  21. return isBalanced(root,height);
  22. }
posted @ 2014-07-29 22:51  purejade  阅读(73)  评论(0编辑  收藏  举报