平衡二叉树
题目详细:LeetCode.110
由题可知:一个平衡二叉树需要满足,其每个节点的左右两个子树的高度差的绝对值不超过 1 。
我们可以依照题意,直接来一波模拟:
- 利用层序遍历(或其他遍历方法)遍历每一个节点
- 通过计算每一个节点的左右子树的高度差来判断是否为平衡二叉树
那么这道题的难点就在于:如何计算树的高度?亦或是如何计算当前节点的高度?
由图及二叉树的概念可知,二叉树的高度和深度是两个不同的定义:
- 二叉树的深度:指
从根节点到当前节点
的最长简单路径边数(从上往下计算) - 二叉树的高度:指
从当前节点到叶子节点
的最长简单路径边数(从下往上计算)
由此我们可以得到计算二叉树深度和高度的遍历方式:
- 计算二叉树的深度,需要从上到下去访问节点,所以使用前序遍历(根左右)
- 计算二叉树的高度,需要从下到上去访问节点,所以使用后序遍历(左右根)
Java解法(模拟,迭代,层序遍历节点,后序遍历计算树的高度):
class Solution {
public boolean isBalanced(TreeNode root) {
if(null == root) return true;
return this.bfs(root);
}
public int getHeight(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
if(null != root) stack.push(root);
int res = 0, height = 0;
while(!stack.isEmpty()){
TreeNode node = stack.pop();
if(null != node){
stack.push(node);
stack.push(null);
height++;
if(null != node.right) stack.push(node.right);
if(null != node.left) stack.push(node.left);
}else{
node = stack.pop();
height--;
}
res = Math.max(res, height);
}
return res;
}
public boolean bfs(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
if(null != root) queue.offer(root);
while(!queue.isEmpty()){
int n = queue.size();
while(n-- > 0){
TreeNode node = queue.poll()