Maximum Depth of Binary Tree Solutions in Java
Number 104
Difficulty Easy
Acceptance 66.1%
Link LeetCode
Solutions
Java solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/// Inspired by : http://www.jiuzhang.com/solutions/maximum-depth-of-binary-tree/// Author : Lei Cao// Date : 2015-10-03package maximumDepthOfBinaryTree;/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/public class maximumDepthOfBinaryTree {public int maxDepth(TreeNode root) {if (root == null) {return 0;}return theDepth(root);}private int theDepth(TreeNode root) {int leftDepth = 1;int rightDepth = 1;if (root.left != null) {leftDepth = theDepth(root.left) + 1;}if (root.right != null) {rightDepth = theDepth(root.right) + 1;}return Math.max(leftDepth, rightDepth);}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/description//// Author : liuyubobobo/// Time : 2017-11-17////// Recursive/// Time Complexity: O(n), where n is the nodes' number in the tree/// Space Complexity: O(h), where h is the height of the treeclass Solution1 {// Definition for a binary tree node.public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }}public int maxDepth(TreeNode root) {if(root == null)return 0;return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/maximum-depth-of-binary-tree/description//// Author : liuyubobobo/// Time : 2017-11-17import java.util.Stack;import javafx.util.Pair;/// Non-recursive/// Time Complexity: O(n), where n is the nodes' number in the tree/// Space Complexity: O(h), where h is the height of the treeclass Solution2 {// Definition for a binary tree node.public class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) { val = x; }}public int maxDepth(TreeNode root) {if(root == null)return 0;Stack<Pair<TreeNode, Integer>> s = new Stack<Pair<TreeNode, Integer>>();s.add(new Pair(root, 1));int res = 0;while(!s.empty()){TreeNode curNode = s.peek().getKey();int depth = s.peek().getValue();s.pop();if(curNode.left == null && curNode.right == null)res = Math.max(res, depth);else{if(curNode.left != null)s.push(new Pair(curNode.left, depth + 1));if(curNode.right != null)s.push(new Pair(curNode.right, depth + 1));}}return res;}}