leetcode Balanced Binary Tree

来源:互联网 发布:怎么从淘宝交水电费 编辑:程序博客网 时间:2024/05/22 10:48

https://oj.leetcode.com/problems/balanced-binary-tree/

判断一棵二叉树是不是平衡二叉树

方法比较笨拙。。。。

用到求深度的函数。


/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public static boolean isBalanced(TreeNode root) {               if(root==null)return true;        int left=root.left==null?0:depth(root.left);        int right=root.right==null?0:depth(root.right);           if(Math.abs(left-right)>1)return false;        return isBalanced(root.left)&&isBalanced(root.right);    }  public static int depth(TreeNode root){  if(root==null)return 0;  //if(root.left==null&&root.right==null)return 1;  int left=root.left==null?0:depth(root.left);  int right=root.right==null?0:depth(root.right);  return (left>right?left:right)+1;  }}



0 0
原创粉丝点击