判断是否为平衡二叉树——题解
平衡二叉树
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&&tqId=11192&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
(记录)平衡二叉树的树结构是左右子树的高度差小于等于1。因此计算左右子树的高度,然后比较大小关系。子树高度的计算采用递归地方式,不断入层。
一棵树的高度等于左右子树中高度比较大的那个。
public class Solution { public boolean IsBalanced_Solution(TreeNode root) { if (root==null) return true; int left = depth(root.left); int right = depth(root.right); if(Math.abs(left-right) > 1) return false; return true; } public int depth(TreeNode root){ if (root==null) return 0; int left = depth(root.left); int right = depth(root.right); return left>right?(left+1):(right+1); } }