题解 | #判断是不是平衡二叉树#
判断是不是平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222
大佬的思路——剪枝!简单明了,无需额外存储空间
二叉树天然可递归!领悟!
- 无需多加非空判断,递归里有!就是终止条件,深度赋予0值,叶子结点深度1
- 但凡子树出现不平衡直接返回false
- 每次递归深度+1
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { return depth(root)!=-1; } int depth(TreeNode root){ if(root==null)return 0; int ldep = depth(root.left); int rdep = depth(root.right); if(ldep==-1)return -1; if(rdep==-1)return -1; return Math.abs(ldep-rdep)<=1?Math.max(ldep,rdep)+1:-1; } }

牛客公司氛围 254人发布