leetcode -- Balanced Binary Tree TODO
生活随笔
收集整理的這篇文章主要介紹了
leetcode -- Balanced Binary Tree TODO
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
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?everynode never differ by more than 1.
?[解題思路]
檢查每個node是否是balanced,大數(shù)據(jù)集掛掉了
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isBalanced(TreeNode root) { 12 // Start typing your Java solution below 13 // DO NOT write main() function 14 if(root == null){ 15 return true; 16 } 17 18 return checkBalance(root); 19 } 20 21 public boolean checkBalance(TreeNode node){ 22 if(node == null){ 23 return true; 24 } 25 int left = getDepth(node.left); 26 int right = getDepth(node.right); 27 if(Math.abs(left - right) > 1){ 28 return false; 29 } 30 return checkBalance(node.left) && checkBalance(node.right); 31 } 32 33 public int getDepth(TreeNode node){ 34 if(node == null){ 35 return 0; 36 } 37 int left = getDepth(node.left); 38 int right = getDepth(node.right); 39 return Math.max(left, right) + 1; 40 } 41 }?
總結(jié)
以上是生活随笔為你收集整理的leetcode -- Balanced Binary Tree TODO的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL更新时Error Code:1
- 下一篇: 【DHCP在企业中的应用】