Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Solution1: recursionRun time complexity is O(n), stack space.
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
else
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
Solution2: iterativeBFS。一直走到最后再返回深度。
Run time complexity is O(n), space complexity is O(n).
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
LinkedList queue = new LinkedList();
int lastNum = 1;
int curNum = 0;
int level = 0;
queue.offer(root);
while(!queue.isEmpty()) {
TreeNode cur = queue.poll();
lastNum--;
if(cur.left != null) {
queue.offer(cur.left);
curNum++;
}
if(cur.right != null) {
queue.offer(cur.right);
curNum++;
}
if(lastNum == 0) {
lastNum = curNum;
curNum = 0;
level++;
}
}
return level;
}
}
No comments:
Post a Comment