博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode(110) Balanced Binary Tree解题报告
阅读量:4134 次
发布时间:2019-05-25

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

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.

解题思路:

求左子树与右子树的深度之差,如果满足,分别递归左子树和右子树。但是这样有大量的重复计算,所以参考网上的一种做法,利用val来存深度,下面附上两次的代码。

public class Solution {    public boolean isBalanced(TreeNode root) {        if(root == null)            return true;        if(Math.abs(Depth(root.left)-Depth(root.right)) > 1)            return false;        return isBalanced(root.left) && isBalanced(root.right);      }    public int Depth(TreeNode root){        if(root == null)            return 0;        return Math.max(Depth(root.left)+1,Depth(root.right)+1);    }}

改进解法:

public class Solution {
public boolean isBalanced(TreeNode root) { if(root == null) return true; Depth(root); return balanced(root); } public boolean balanced(TreeNode root){ int l=0,r=0; if(root == null) return true; if(root.left != null) l = root.left.val; if(root.right != null) r = root.right.val; if(Math.abs(l-r) > 1) return false; return balanced(root.left) && balanced(root.right); } public int Depth(TreeNode root){ if(root == null) return 0; root.val = Math.max(Depth(root.left)+1,Depth(root.right)+1); return root.val; }

转载地址:http://rtivi.baihongyu.com/

你可能感兴趣的文章
zju 1006 zoj 1006
查看>>
【虚拟机】虚拟化架构与系统部署(Windows系统安装)
查看>>
字节跳动安卓开发实习生面试分享
查看>>
好书分享之——《能力陷进》
查看>>
阅读笔记《c++ primer》
查看>>
阅读笔记《C++标准程序库》
查看>>
基于mirror driver的windows屏幕录像
查看>>
C语言8
查看>>
Qt实现简单延时
查看>>
qml有关矩形说明
查看>>
在qt中使用QSplitter设置初始比例setStretchFactor失效的解决方法
查看>>
repeater的使用
查看>>
qt msvc编译中文乱码解决
查看>>
qt中TextField输入框无法输入中文解决办法
查看>>
qt实现点击出现窗口,点击其他任何地方窗口消失
查看>>
QML DropArea拖拉文件事件
查看>>
CORBA links
查看>>
读后感:>
查看>>
ideas about sharing software
查看>>
different aspects for software
查看>>