时间复杂度:O(N) 空间复杂度:O(N)
class Solution { public boolean isBalanced(TreeNode root) { return recur(root) != -1; } private int recur(TreeNode root) { if (root == null) return 0; int left = recur(root.left); if(left == -1) return -1; int right = recur(root.right); if(right == -1) return -1; return Math.abs(left - right) < 2 ? Math.max(left, right) + 1 : -1; } }时间复杂度:O(NlogN) 空间复杂度:O(N)
public boolean isBalanced(TreeNode root) { if(root == null) return true; int l = maxDepth(root.left); int r = maxDepth(root.right); if(Math.abs(r-l)>1){ return false; } else{ return isBalanced(root.left) && isBalanced(root.right); } } public int maxDepth(TreeNode root) { if(root == null) return 0; return Math.max(maxDepth(root.left),maxDepth(root.right))+1; }常见的 DFS : 先序遍历、中序遍历、后序遍历; 常见的 BFS : 层序遍历(即按层遍历)。
转载链接:https://leetcode-cn.com/problems/ping-heng-er-cha-shu-lcof/solution/mian-shi-ti-55-ii-ping-heng-er-cha-shu-cong-di-zhi/