【Leetcode】Balanced Binary Tree

题目链接:https://leetcode.com/problems/balanced-binary-tree/

题目:

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.

思路:

根据结点高度,递归判断是否满足平衡树定义。此题跟Kth Smallest Element in a BST 做法类似,在遍历过程中遇到满足某条件的结点时,将结果放到全局变量中,如果没遇到最终递归返回的就是全局变量的初始值,否则返回的变化后的值。   就像一个开关,达到条件时,就变化;没达到条件,就不变。 因为判断每个结点需要求该结点左右高度,所以时间复杂度是O(n^2)。

算法:

	public boolean isBalanced(TreeNode root) {
		if (root == null)
			return true;
		int h1 = heightTree(root.left);
		int h2 = heightTree(root.right);
		boolean flag = Math.abs(h1 - h2) > 1 ? false : true;
		if (flag == false) { // 当不满足平衡树定义时,将结果放到全局变量中。
			result = false;
		} // 如果所有结点都平衡,则result不变还时初始值 true
		isBalanced(root.left);
		isBalanced(root.right);
		return result;
	}

	public int heightTree(TreeNode p) {
		if (p == null)
			return 0;
		int h1 = heightTree(p.left);
		int h2 = heightTree(p.right);
		return h1 > h2 ? h1 + 1 : h2 + 1;
	}



你可能感兴趣的:(【Leetcode】Balanced Binary Tree)