Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
Thoughts:
When a tree node is considered as "balanced", the left and the right leaf nodes are both "balanced", and the difference between height of left and right leaf is at most 1. A recursive procedure can then be designed.
Also worthy to mention, there are several common used self-balanced binary tree alogorithms: AVL Tree and RB Tree.
Solution:
- /**
- * Definition for binary tree
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
- * };
- */
- class Solution {
- public:
- pair<bool, int> TraverseProc(const TreeNode* node)
- {
- if (node == nullptr)
- return make_pair(true, 0);
- // check left branch
- pair<bool, int> left_balance=TraverseProc(node->left);
- if (!left_balance.first) return make_pair(false, 0);
- // check right branch
- pair<bool, int> right_balance=TraverseProc(node->right);
- if (!right_balance.first) return make_pair(false, 0);
- // check the current node
- int balance_factor = left_balance.second - right_balance.second;
- if (balance_factor>1 || balance_factor<-1)
- return make_pair(false, 0);
- else
- return make_pair(true, max(left_balance.second, right_balance.second)+1);
- }
- bool isBalanced(TreeNode *root) {
- // Note: The Solution object is instantiated only once and is reused by each test case.
- return TraverseProc(root).first;
- }
- };
No comments:
Post a Comment