Maximum Depth of Binary Tree

// Solution 1
class Solution {
		public int maxDepth(TreeNode root) {
				if (root == null) return 0;
				int max_left = maxDepth(root.left);
				int max_right = maxDepth(root.right);
				return Math.max(max_left, max_right) + 1;
		}
}


// Solution 2
class Solution {
		public int maxDepth(TreeNode root) {
				return getHeight(root);
		}
		
		public int getHeight(TreeNode root) {
			if (root == null) return 0; //corner case
			
			int left = getHeight(root.left);
			int right = getHeight(root.right);
			
			return Math.max(left, right) + 1;
		}
		
		public int getMinHeight(TreeNode root) {
			if (root == null) return 0; //corner case
			
			int left = getHeight(root.left);
			int right = getHeight(root.right);
			
			return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1 ;
		}
}


最后更新于

这有帮助吗?