使用深度优先搜索(depth first search)算法遍历二叉树,有两种方式:
This problem is generally believed to have two solutions: the top down approach and the bottom up way.
(https://oj.leetcode.com/discuss/22898/the-bottom-up-o-n-solution-would-be-better)
从下往上遍历,时间复杂度为O(n)
从上往下遍历,时间复杂度为O(nlogn)
另外需要注意的是,C语言中没有max函数,需要自己定义;abs函数C语言支持
bottom up way
<span style="font-family:Microsoft YaHei;font-size:14px;">/**
* Definition for binary tree
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int max(int a,int b){
if(a > b) return a;
else return b;
}
int dfsHeight(struct TreeNode *root){
if(root == NULL) return 0;
int leftHeight = dfsHeight(root->left);
if(leftHeight == -1) return -1;
int rightHeight = dfsHeight(root->right);
if(rightHeight == -1) return -1;
if(abs(leftHeight - rightHeight) > 1) return -1;
return max(leftHeight,rightHeight) + 1;
}
bool isBalanced(struct TreeNode *root) {
return dfsHeight(root) != -1;
}</span>