dya 2.c++語法
阿新 • • 發佈:2021-12-02
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點的左右兩個子樹的高度差的絕對值不超過 1 。
來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/balanced-binary-tree
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。
心之所向,素履以往 生如逆旅,一葦以航class Solution { private Helper solve(TreeNode root) { if (root == null) { return new Helper(true, 0); } Helper left = solve(root.left); Helper right = solve(root.right); return new Helper(left.isBalanced && right.isBalanced && Math.abs(left.height - right.height) <= 1, Math.max(left.height, right.height) + 1); } public boolean isBalanced(TreeNode root) { if (root == null) { return true; } return solve(root).isBalanced; } } class Helper { boolean isBalanced; int height; public Helper(boolean isBalanced, int height) { this.isBalanced = isBalanced; this.height = height; } } 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; } }