程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode 110. Balanced Binary Tree 遞歸求解

LeetCode 110. Balanced Binary Tree 遞歸求解

編輯:C++入門知識

LeetCode 110. Balanced Binary Tree 遞歸求解


110. Balanced Binary Tree

My SubmissionsTotal Accepted:97926Total Submissions:292400Difficulty: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 ofeverynode never differ by more than 1.

Subscribeto see which companies asked this question

Show Tags Show Similar Problems Have you met this question in a real interview? Yes No

判斷一棵樹是否是平衡二叉樹。BST的遞歸定義:當一棵樹的左右兩棵子樹的高度只差不超過1,那麼該樹是平衡二叉樹。

用後根遍歷求解。先計算兩棵子樹的高度差。

我的AC代碼

public class BalancedBinaryTree {
	static boolean ok = true;
	
	public static void main(String[] args) {
		TreeNode n1 = new TreeNode(1);
		TreeNode n2 = new TreeNode(2);
		n1.left = n2;
		System.out.println(isBalanced(n1));
	}

	public static boolean isBalanced(TreeNode root) {
        ok = true;
        dfs(root);
        return ok;
    }
	
	public static int dfs(TreeNode root) {
		if(root == null || !ok) return 0;
		int ha = dfs(root.left);
		int hb = dfs(root.right);
		
		if(Math.abs(ha - hb) > 1) ok = false;
		return Math.max(ha, hb) + 1;
	}
}

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved