题目链接
后序遍历高度,高度判断是否平衡
前序遍历深度
递归
java">/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public boolean isBalanced(TreeNode root) {if(root == null){return true;}return getHeight(root) == -1 ? false : true;}// -1表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度public int getHeight(TreeNode root){if(root == null){return 0;}int lh = getHeight(root.left);if(lh == -1){return -1;}int rh = getHeight(root.right);if(rh == -1){return -1;}// 判断当前传入节点为根节点的二叉树是否为平衡二叉树:求左子树与右子树高度差值绝对值 <= 则为平衡二叉树int res;if(Math.abs(lh - rh) > 1){res = -1;}else{res = 1 + Math.max(lh,rh);}return res;}
}