加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

LeetCode_110. Balanced Binary Tree

发布时间:2020-12-14 04:40:19 所属栏目:大数据 来源:网络整理
导读:? 110.?Balanced Binary Tree Easy Given a binary tree,determine if it is height-balanced. For this problem,a height-balanced binary tree is defined as: a binary tree in which the depth of the two subtrees of? every ?node never differ by mor

?

110.?Balanced Binary Tree

Easy

Given a binary tree,determine if it is height-balanced.

For this problem,a height-balanced binary tree is defined as:

a binary tree in which the depth of the two subtrees of?every?node never differ by more than 1.

Example 1:

Given the following tree?[3,9,20,null,15,7]:

    3
   /   9  20
    /     15   7

Return true.

Example 2:

Given the following tree?[1,2,3,4,4]:

       1
      /      2   2
    /    3   3
  /  4   4

Return false.

?

package leetcode.easy;

public class BalancedBinaryTree {
	@org.junit.Test
	public void test1() {
		TreeNode tn11 = new TreeNode(3);
		TreeNode tn21 = new TreeNode(9);
		TreeNode tn22 = new TreeNode(20);
		TreeNode tn33 = new TreeNode(15);
		TreeNode tn34 = new TreeNode(7);
		tn11.left = tn21;
		tn11.right = tn22;
		tn21.left = null;
		tn21.right = null;
		tn22.left = tn33;
		tn22.right = tn34;
		tn33.left = null;
		tn33.right = null;
		tn34.left = null;
		tn34.right = null;
		System.out.print(isBalanced(tn11));
	}

	@org.junit.Test
	public void test2() {
		TreeNode tn11 = new TreeNode(1);
		TreeNode tn21 = new TreeNode(2);
		TreeNode tn22 = new TreeNode(2);
		TreeNode tn31 = new TreeNode(3);
		TreeNode tn32 = new TreeNode(3);
		TreeNode tn41 = new TreeNode(4);
		TreeNode tn42 = new TreeNode(4);
		tn11.left = tn21;
		tn11.right = tn22;
		tn21.left = tn31;
		tn21.right = tn32;
		tn22.left = null;
		tn22.right = null;
		tn31.left = tn41;
		tn31.right = tn42;
		tn32.left = null;
		tn32.right = null;
		tn41.left = null;
		tn41.right = null;
		tn42.left = null;
		tn42.right = null;
		System.out.print(isBalanced(tn11));
	}

	public boolean isBalanced(TreeNode root) {
		if (null == root) {
			return true;
		} else {
			return (Math.abs(maxDepth(root.left) - maxDepth(root.right)) <= 1) && isBalanced(root.left)
					&& isBalanced(root.right);
		}
	}

	private static int maxDepth(TreeNode root) {
		if (null == root) {
			return 0;
		} else {
			return 1 + Math.max(maxDepth(root.left),maxDepth(root.right));
		}
	}
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读