摘要
本博文主要介绍平衡二叉树问题包括,二叉树的高度差,是否为平衡二叉树,有序链表转二叉搜索树,将二叉搜索树变平衡等。
一、平衡二叉树详解
1.1 判断二叉树是否平衡
/*** 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;}return getHeight(root) == -1 ? false : true;}public int getHeight(TreeNode root) {if (root == null) {return 0;}int leftH = getHeight(root.left);if (leftH == -1) {return -1;}int rightH = getHeight(root.right);if (rightH == -1) {return -1;}return Math.abs(leftH - rightH) > 1 ? -1 : 1 + Math.max(leftH, rightH);}
}
二·、平衡二叉树相关问题
110. 平衡二叉树
109. 有序链表转换二叉搜索树
1382. 将二叉搜索树变平衡
博文参考
《leetcode》