Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Balanced Binary Tree

Posted on January 12, 2018July 26, 2020 by braindenny

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



Similar Problems:

  • Count Complete Tree Nodes
  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #binarytree, #heightoftree

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 depth of the two subtrees of every node never differ by more than 1.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/balanced-binary-tree
// Basic Ideas: recursive
//
// Complexity: Time O(n), Space O(h)
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func dfs(root *TreeNode) (int, bool) {
    if root == nil { return 0, true  }
    h1, ok1 := dfs(root.Left)
    if ! ok1 {
        return 0, false
    }
    h2, ok2 := dfs(root.Right)
    if ! ok2 {
        return 0, false
    }
    if h1 < h2 {
        h1, h2 = h2, h1
    }
    if h1-h2>1 {
        return 0, false
    }
    return h1+1, true
}

func isBalanced(root *TreeNode) bool {
    _, ok := dfs(root)
    return ok
}
## https://code.dennyzhang.com/balanced-binary-tree
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        (status, _level) = self._isBalanced(root)
        return status

    def _isBalanced(self, root):
        """
        :type root: TreeNode
        :rtype: (bool, level)
        """
        if root is None:
            return (True, 0)
        if root.left is None and root.right is None:
            return (True, 1)

        (l_status, l_level) = self._isBalanced(root.left)
        if l_status is False:
            return (False, -1)
        (r_status, r_level) = self._isBalanced(root.right)
        if r_status is False:
            return (False, -1)

        if (abs(l_level - r_level)>1):
            return (False, -1)
        return (True, max(l_level, r_level) + 1)
linkedin
github
slack

Post Views: 7
Posted in BasicTagged #binarytree, heightoftree

Post navigation

LeetCode: Binary Tree Paths
LeetCode: Valid Anagram

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.