How to Check Balanced Binary Tree in C/C++?


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.

Submit your solution: https://leetcode.com/problems/balanced-binary-tree/

balanced-tree-or-not How to Check Balanced Binary Tree in C/C++? c / c++ data structure leetcode online judge

balanced-tree-or-not

Recursion

We have solved many many binary tree puzzles using recursive, and we can declare a tree in C/C++ using pointers.

1
2
3
4
5
6
7
8
9
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

We need to define a function that computes the height, which will be the maximum distance between any leaf to the root.

1
2
3
4
int getHeight(TreeNode* root) {
    return root == NULL ? 0 : 1 +
        max(getHeight(root->left), getHeight(root->right));
}
int getHeight(TreeNode* root) {
    return root == NULL ? 0 : 1 +
        max(getHeight(root->left), getHeight(root->right));
}

The solution will be to check if both sub trees are balanced and the height difference is at most 1.

1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:   
    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        }
        int left = getHeight(root->left);
        int right = getHeight(root->right);
        return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};
class Solution {
public:   
    bool isBalanced(TreeNode* root) {
        if (root == NULL) {
            return true;
        }
        int left = getHeight(root->left);
        int right = getHeight(root->right);
        return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
    }
};

Recursion still gives the most concise solution although it may have stack-over-flow problem when the tree depth exceeds the limit.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
355 words
Last Post: How to Add Binary String in C/C++?
Next Post: How to Validate Binary Search Tree in C/C++?

The Permanent URL is: How to Check Balanced Binary Tree in C/C++?

2 Comments

  1. sabri

Leave a Reply