输入一棵二叉树的根节点,判断该树是不是平衡二叉树。如果某二叉树中任意节点的左右子树的深度相差不超过1,那么它就是一棵平衡二叉树。
思考递归(例如对于关于树的相关操作):要从树叶到树根思考代码的运行过程!
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } class Solution { public boolean isBalanced(TreeNode node) { return help(node) != -1; } private int help(TreeNode node) { if (node == null) return 0; int lt = 0; if ((lt = help(node.left)) == -1) return -1; int rt = 0; if ((rt = help(node.right)) == -1) return -1; return Math.abs(lt-rt) <=1?Math.max(lt,rt) + 1:-1; } }
题目来源:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof