平衡二叉树
难度:简单
题目描述
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树_每个节点_ 的左右两个子树的高度差的绝对值不超过 1 。
示例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
题解
利用递归的思想对整棵树进行遍历,如果左子树深度减右子树深度大于1
,那么将返回值设定为-1
,如果不是,则将返回值的定为1 + 左右子树深度的最大值
,最终判定最后的返回值是否为-1
,如果是-1
,那么就不是二叉搜索树,反之则是二叉搜索树
想法代码
using System;public class TreeNode
{public int val;public TreeNode left;public TreeNode right;public TreeNode(int val = 0, TreeNode left = null, TreeNode right = null){this.val = val;this.left = left;this.right = right;}
}public class Solution
{public static void Main(string[] args){TreeNode root= new TreeNode{val= 3,left = new TreeNode(9),right = new TreeNode{val= 20,left = new TreeNode(15),right= new TreeNode(7)}};Solution solution = new Solution();bool ans = solution.IsBalanced(root);Console.WriteLine(ans);}public bool IsBalanced(TreeNode root){return !(BackTrack(root) == -1);}public int BackTrack(TreeNode root){if (root == null){return 0;}int leftH = BackTrack(root.left);if (leftH == -1){return -1;}int rightH = BackTrack(root.right);if (rightH == -1){return -1;}return Math.Abs(leftH - rightH) > 1 ? -1 : (1 + Math.Max(leftH, rightH));}
}