判断二叉树是否为平衡二叉树

题目描述

输入一棵二叉树,判断该二叉树是否是平衡二叉树。
 
思路:基于后序遍历,边遍历边判断,时间复杂度为O(n)
 1 class Solution {
 2 public:
 3     int DFS(TreeNode *pRoot, bool &isBalanced)
 4     {
 5         int left=0;
 6         int right=0;
 7         if(pRoot->left)left=DFS(pRoot->left, isBalanced);
 8         if(pRoot->right)right=DFS(pRoot->right, isBalanced);
 9         int dif=left-right;
10         if(dif<-1 || dif>1)isBalanced=false;
11         return left>right ? left+1:right+1;
12     }
13     bool IsBalanced_Solution(TreeNode* pRoot) {
14         if(pRoot==NULL)return true;
15         bool isBalanced=true;
16         DFS(pRoot, isBalanced);
17         return isBalanced;
18     }
19 };

 

posted @ 2018-01-31 17:23  jeysin  阅读(146)  评论(0编辑  收藏  举报