博文中会简要介绍Leetcode P0110题目分析及解题思路。
“Balanced Binary Tree”是一道比较基础的题目,利用深度优先搜索,这里采取递归回溯的方法,每次获取当前树结点的左右子树高度,判断是否平衡。
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.
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isBalanced(TreeNode root) {
if (root == null)
return true;
this.traverse(root);
return this.balanced;
}
private boolean balanced = true;
private int traverse(TreeNode curr) {
if (curr.left == null && curr.right == null)
return 1;
int leftHeight = 0, rightHeight = 0;
if (curr.left != null)
leftHeight = this.traverse(curr.left);
if (curr.right != null)
rightHeight = this.traverse(curr.right);
this.balanced = this.balanced && (Math.abs(leftHeight-rightHeight) <= 1);
return Math.max(leftHeight+1, rightHeight+1);
}
}
以下是C++的题解代码实现。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isBalanced(TreeNode* root) {
this->Traverse(root);
return this->balanced;
}
private:
bool balanced = true;
int Traverse(TreeNode *curr) {
if (!curr)
return 0;
int lh = 0, rh = 0;
if (curr->left)
lh = this->Traverse(curr->left);
if (curr->right)
rh = this->Traverse(curr->right);
this->balanced = this->balanced && (abs(lh-rh) <= 1);
return max(lh, rh)+1;
}
};