Balanced Binary Tree - Tree - Easy - LeetCode
💻 coding

Balanced Binary Tree - Tree - Easy - LeetCode

1 min read 185 words
1 min read
ShareWhatsAppPost on X
  • 1A height-balanced binary tree has left and right subtrees differing in height by no more than 1.
  • 2The provided solution uses a recursive approach to determine if a binary tree is height-balanced.
  • 3The time complexity of the algorithm is O(n) while the space complexity is O(1).

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"A height-balanced binary tree has left and right subtrees differing in height by no more than 1."

Balanced Binary Tree - Tree - Easy - LeetCode

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as:

a binary tree in which the left and right subtrees of every node differ in height by no more than 1.

Example 1:

Given the following tree [3,9,20,null,null,15,7]:

3 / \ 9 20 / \ 15 7 Return true.

Example 2:

Given the following tree [1,2,2,3,3,null,null,4,4]:

1 / \ 2 2 / \ 3 3 / \ 4 4 Return false.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * public int val;
 * public TreeNode left;
 * public TreeNode right;
 * public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
public class Solution {
 public bool IsBalanced(TreeNode root) {
 if(root==null){
 return true;
 }
 int left = Helper(root.left);
 int right = Helper(root.right);
 if(Math.Abs(left-right)>1){
 return false;
 }
 return IsBalanced(root.left)&&IsBalanced(root.right);
 }
 
 private int Helper(TreeNode root){
 if(root==null){
 return 0;
 }
 int left = Helper(root.left);
 int right = Helper(root.right);
 return 1+Math.Max(left,right);
 }
 
}

Time Complexity: O(n)

Space Complexity: O(1)

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

sumitc91

Published on 6 October 2020 · 1 min read · 185 words

Part of AskGif Blog · coding

You might also like

Balanced Binary Tree - Tree - Easy - LeetCode | AskGif Blog