Topic describes

Given a binary tree, determine if it is a highly balanced binary tree. // In this case, a height balanced binary tree is defined as: // The absolute value of the height difference between the left and right subtrees of each node of a binary tree is no more than 1.Copy the code

Answer key

/** * 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; *} *} */ / 55.2 balanced binary tree // // : 88 ms, beat 5.18% of all Java commits // memory consumption: Class Solution {public Boolean res = true; public boolean isBalanced(TreeNode root) { if (root == null) return res; preOrder(root); return res; } private void preOrder(TreeNode root) { if (root == null) return; if (Math.abs(searchDepth(root.left) - searchDepth(root.right)) > 1) res = false; preOrder(root.left); preOrder(root.right); } private int searchDepth(TreeNode root) { if (root == null) return 0; return 1 + Math.max(searchDepth(root.left), searchDepth(root.right)); }}Copy the code
// Beat 99.99% of all Java commits in 1 ms // memory consumption: 38.3 MB, Class Solution {public Boolean isBalanced(TreeNode root) {if (root == null) return true; if (Math.abs(depth(root.left) - depth(root.right)) > 1) { return false; } return isBalanced(root.left) && isBalanced(root.right); } public int depth(TreeNode root) { if (root == null) return 0; return Math.max(depth(root.left), depth(root.right)) + 1; }}Copy the code