LeetCode-Easy刷題(24) Balanced Binary Tree
阿新 • • 發佈:2018-12-04
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.
給定一棵二叉樹,確定它是否是高度平衡的。 對於這個問題,一個高度平衡二叉樹定義為一個二叉樹,其深度兩子樹節點不會相差超過1
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.
給定一棵二叉樹,確定它是否是高度平衡的。 對於這個問題,一個高度平衡二叉樹定義為一個二叉樹,其深度兩子樹節點不會相差超過1
//遞迴 深度優先 維護深度 public boolean isBalanced(TreeNode root) { return isBalancedHelp(root) >=0; } public int isBalancedHelp(TreeNode root){ if(root ==null){ //遞迴正常結束條件 return 0; } int left = isBalancedHelp(root.left);//深度 int right = isBalancedHelp(root.right);//同層 right if(left < 0 || right <0){ //不平衡提前結束條件 return -1; } if(Math.abs(left - right)>1){//判斷是否不平衡 return -1; } return Math.max(left, right)+1;//維護到當前節點最大深度 }