平衡二叉树判定

来源:互联网 发布:origin如何画图软件 编辑:程序博客网 时间:2024/05/23 17:16


import java.util.*;/*public class TreeNode {    int val = 0;    TreeNode left = null;    TreeNode right = null;    public TreeNode(int val) {        this.val = val;    }}*/public class Balance {           // write code here boolean r = true;    public boolean isBalance(TreeNode root) {        // write code here    getDepth( root);    return r;    }    public int getDepth(TreeNode root){    if(root == null)     return 0;    int left = getDepth(root.left);    int right = getDepth(root.right);    if(Math.abs(left-right)>1)    r = false;    return left < right?right+1 : left+1;    }}

题目描述

实现一个函数,检查二叉树是否平衡,平衡的定义如下,对于树中的任意一个结点,其两颗子树的高度差不超过1。

给定指向树根结点的指针TreeNode* root,请返回一个bool,代表这棵树是否平衡。

原创粉丝点击