本文主要是介绍平衡二叉树——JZ39,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://www.nowcoder.com/practice/8b3b95850edb4115918ecebdf1b4d222?tpId=13&tags=&title=&difficulty=0&judgeStatus=0&rp=1
描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树
平衡二叉树(Balanced Binary Tree),具有以下性质:它是一棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
注:我们约定空树是平衡二叉树。
示例1
输入:
{1,2,3,4,5,6,7}
复制返回值:
true
public class Jz39_IsBalanced_Solution {private boolean ans = true;public boolean IsBalanced_Solution(TreeNode root) {judge(root);return ans;}public int judge(TreeNode node) {if (null == node || !ans) {return 0;}int leftDepth = judge(node.left);int rightDepth = judge(node.right);if (leftDepth - rightDepth >= 2 || leftDepth - rightDepth <= -2) {ans = false;return 0;}return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;}public class TreeNode {int val = 0;TreeNode left = null;TreeNode right = null;public TreeNode(int val) {this.val = val;}}
}
这篇关于平衡二叉树——JZ39的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!