剑指Offer平衡二叉树(树)
Posted AIAS编程有道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了剑指Offer平衡二叉树(树)相关的知识,希望对你有一定的参考价值。
题目
输入一棵二叉树,判断该二叉树是否是平衡二叉树
思路
平衡二叉树:某节点的左右子树深度差绝对值不超过1。利用递归求左右子树的深度,以判断这颗树是不是平衡的。
参考代码
Java
1import java.util.HashMap;
2public class Solution {
3 public boolean IsBalanced_Solution(TreeNode root) {
4 if (root == null) return true;
5 int left = deep(root.left); // 获取左子树深度
6 int right = deep(root.right);// 获取右子树深度
7 int diff = left - right;
8 if (diff > 1 || diff < -1) return false;
9 return IsBalanced_Solution(root.left) && IsBalanced_Solution(root.right);
10 }
11 public int deep(TreeNode root){
12 if (root == null) return 0;
13 int left = deep(root.left); // 获取左子树的深度
14 int right = deep(root.right); // 获取右子树的深度
15 return left > right ? left + 1:right + 1;
16 }
17}
Python
1# -*- coding:utf-8 -*-
2# class TreeNode:
3# def __init__(self, x):
4# self.val = x
5# self.left = None
6# self.right = None
7class Solution:
8 def IsBalanced_Solution(self, pRoot):
9 # write code here
10 if not pRoot:return True
11 left = self.deep(pRoot.left)
12 right = self.deep(pRoot.right)
13 diff = left - right
14 if diff > 1 or diff < -1: return False
15 return self.IsBalanced_Solution(pRoot.left) and self.IsBalanced_Solution(pRoot.right)
16 def deep(self, root):
17 if not root :return 0
18 left = self.deep(root.left)
19 right = self.deep(root.right)
20 return left + 1 if left > right else right + 1
以上是关于剑指Offer平衡二叉树(树)的主要内容,如果未能解决你的问题,请参考以下文章