前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Baozi Training Leetcode Solution 110: Balanced Binary Tree

Baozi Training Leetcode Solution 110: Balanced Binary Tree

作者头像
包子面试培训
发布2019-08-08 22:23:48
4260
发布2019-08-08 22:23:48
举报
文章被收录于专栏:包子铺里聊IT包子铺里聊IT

Problem Statement

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.

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.

Problem link

Video Tutorial

You can find the detailed video tutorial here

  • Youtube
  • B站

Thought Process

As described in the problem, it is intuitive to solve this problem recursively, especially given this is a tree related problem. What we can do is get the height of the left sub tree, compared with the right sub tree, then do the logics to see if it’s balanced or not. If at certain level either the left or right sub tree is not balanced, then entire Tree is not balanced. Classic usage for post order traversal.

Solutions

 1 public boolean isBalanced(TreeNode root) {
 2         return maxHeight(root) != -1;
 3     }
 4     
 5     // if -1, means it is not a balanced tree, since it will also return the normal height(int), so boolean is not an option.
 6     // Kinda of a hack for the return type.
 7     // @return -1 means it's already not a balanced tree, else t;he tree height
 8     public int maxHeight(TreeNode root) {
 9         if (root == null) {
10             return 0;
11         }
12         
13         int l = maxHeight(root.left);
14         int r = maxHeight(root.right);
15 
16         // a classic usage of post order traversalß
17         if (l == -1 || r == -1 || Math.abs(l - r) > 1) {
18             return -1;
19         }
20         return Math.max(l, r) + 1;
21     }
Post order traversal using recursion

Calculate the height of the left subtree, calculate the height of the right subtree, then compare. If it's already not balanced, return -1 and directly return

Time Complexity: O(N), N is the total tree nodes since it is visited once and only once

Space Complexity: O(1), No extra space is needed

References

  • Leetcode discussion
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-08-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 包子铺里聊IT 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Problem Statement
  • Video Tutorial
  • Thought Process
  • Solutions
    • Post order traversal using recursion
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档