- Top-down recursion
/** * 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; } int left = getHeight(root.left); int right = getHeight(root.right); if(Math.abs(left - right) > 1){ return false; } return isBalanced(root.left) && isBalanced(root.right); } private int getHeight(TreeNode root){ if(root == null){ return 0; } int leftHeight = getHeight(root.left); int rightHeight = getHeight(root.right); int height = Math.max(leftHeight, rightHeight) + 1; return height; } } - Bottom-up recursion
/** * 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) { return checkDepth(root) != -1; } private int checkDepth(TreeNode root){ if(root == null){ return 0; } int left = checkDepth(root.left); if(left == -1){ return -1; } int right = checkDepth(root.right); if(right == -1){ return -1; } if(Math.abs(left - right) < 2){ return Math.max(left, right) + 1; }else{ return -1; } } }
LeetCode 110. Balanced Binary Tree
最新推荐文章于 2023-11-11 23:37:07 发布
本文介绍了两种检查二叉树是否平衡的递归算法:顶向下递归和底向上递归。通过计算每个子树的高度并比较左右子树高度差是否超过1来判断树是否平衡。顶向下递归先计算高度再判断平衡性,而底向上递归在计算高度的同时进行判断。
253

被折叠的 条评论
为什么被折叠?



