博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Balanced Binary Tree -- LeetCode
阅读量:4685 次
发布时间:2019-06-09

本文共 1562 字,大约阅读时间需要 5 分钟。

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.

思路:这题有两种方法。

Top down approach

设计一个depth函数,递归地返回一个子树的深度。

一个BST平衡的条件为:为空;或者左右子树皆平衡,且左右子树的深度相差不超过1。

1 class Solution { 2 public: 3     int depth(TreeNode *root) 4     { 5         if (!root) return 0; 6         return max(depth(root->left), depth(root->right)) + 1; 7     } 8     bool isBalanced (TreeNode *root) { 9         if (!root) return true;10         int left = depth(root->left);11         int right = depth(root->right);12         return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right); 13     }14 };

复杂度分析:

用master theory: depth函数为T(n) = 2T(n/2) + 1,为O(n);

isBalanced函数为T(n) = 2T(n/2) + O(n),为O(nlogn)。

如果这种方法想让时间复杂度降为O(n),则需要用map记录下每个子树的深度,以后就不需要再计算了。但空间复杂度为O(n)。

Bottom up approach

自底向上进行判断。使用一个help函数,若子树为平衡的,则返回该子树的深度,否则返回0。该方法每个节点只访问一遍,因此复杂度为O(n)。

1 class Solution { 2 public: 3     int help(TreeNode *root) 4     //balanced -- result >= 0 5     //not balanced -- result = -1 6     { 7         if (!root) return 0; 8         int left = help(root->left); 9         if (left == -1) return -1;10         int right = help(root->right);11         if (right == -1) return -1;12         if (abs(left - right) > 1) return -1;13         return max(left, right) + 1;14     }15     bool isBalanced (TreeNode *root) {16         return help(root) != -1;17     }18 };

 

转载于:https://www.cnblogs.com/fenshen371/p/5167920.html

你可能感兴趣的文章
Git Day02,工作区,暂存区,回退,删除文件
查看>>
学前班
查看>>
关于自关联1
查看>>
hdu-1814(2-sat)
查看>>
谷歌浏览器,添加默认搜索引擎的搜索地址
查看>>
数据结构化与保存
查看>>
转 python新手容易犯的6个错误
查看>>
第四节 -- 列表
查看>>
决策树
查看>>
如何避免在简单业务逻辑上面的细节上面出错
查看>>
Linux shell 命令判断执行语法 ; , && , ||
查看>>
vim代码格式化插件clang-format
查看>>
RTP Payload Format for Transport of MPEG-4 Elementary Streams over http
查看>>
Java环境变量设置
查看>>
【JBPM4】判断节点decision 方法3 handler
查看>>
filter 过滤器(监听)
查看>>
c语言基础知识要点
查看>>
node启动时, listen EADDRINUSE 报错;
查看>>
杭电3466————DP之01背包(对状态转移方程的更新理解)
查看>>
kafka中的消费组
查看>>