平衡二叉树
描述
- 给定一个二叉树,判断它是否是 平衡二叉树
示例 1
输入:root = [3,9,20,null,null,15,7]
输出:true
示例 2
输入:root = [1,2,2,3,3,null,null,4,4]
输出:false
示例 3
输入:root = []
输出:true
提示
- 树中的节点数在范围 [0, 5000] 内
- - 1 0 4 10^4 104 <= Node.val <= 1 0 4 10^4 104
Typescript 版算法实现
1 ) 方案1: 自顶向下的递归
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function isBalanced(root: TreeNode | null): boolean {
if (!root) return true;
const height = (node: TreeNode | null): number => {
if (!node) return 0;
return Math.max(height(node.left), height(node.right)) + 1;
}
const leftHeight = height(root.left);
const rightHeight = height(root.right);
return (
Math.abs(leftHeight - rightHeight) <= 1 &&
isBalanced(root.left) &&
isBalanced(root.right)
);
}
2 ) 方案2: 自底向上的递归
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function isBalanced(root: TreeNode | null): boolean {
function height(node: TreeNode | null): number {
if (!node) return 0;
const leftHeight = height(node.left);
const rightHeight = height(node.right);
// 如果左右子树中任意一个不平衡,或者高度差超过1,则当前树也不平衡
if (leftHeight === -1 || rightHeight === -1 || Math.abs(leftHeight - rightHeight) > 1) {
return -1;
}
return Math.max(leftHeight, rightHeight) + 1;
}
return height(root) !== -1;
}
标签:node,right,TreeNode,val,Ts,110,left,null,二叉树
From: https://blog.csdn.net/Tyro_java/article/details/144994166