My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
return getDepth(root);
}
private int getDepth(TreeNode root) {
if (root == null)
return 0;
int depth1 = getDepth(root.left);
int depth2 = getDepth(root.right);
return 1 + Math.max(depth1, depth2);
}
}
My test result:
简单题。。。为了完成今天5道题的目标,但是又刷不动了,选了这道简单题。
没什么好分析的。
**
总结: DFS, bottom-up, post-order
**
Anyway, Good luck, Richardo!
My code:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode root) {
return root == null ? 0 : 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}
}
一行解决问题。
fuck. 也就只能在简单题里面装个逼了
Anyway, Good luck, Richardo!
DFS recursion
My code:
/**
* Definition for a binary tree node.
* 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;
}
int left = maxDepth(root.left);
int right = maxDepth(root.right);
return 1 + Math.max(left, right);
}
}
pre-order
DFS iteration
My code:
/**
* Definition for a binary tree node.
* 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;
}
Stack st = new Stack();
Stack value = new Stack();
st.push(root);
value.push(1);
int max = 0;
while (!st.isEmpty()) {
TreeNode node = st.pop();
int temp = value.pop();
max = Math.max(max, temp);
if (node.left != null) {
st.push(node.left);
value.push(temp + 1);
}
if (node.right != null) {
st.push(node.right);
value.push(temp + 1);
}
}
return max;
}
}
用两个栈的方法很巧妙。同时暂存头结点的depth -> temp
BFS
My code:
/**
* Definition for a binary tree node.
* 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;
}
Queue q = new LinkedList();
q.offer(root);
int counter = 0;
while (!q.isEmpty()) {
counter++;
int size = q.size();
for (int i = 0; i < size; i++) {
TreeNode node = q.poll();
if (node.left != null) {
q.offer(node.left);
}
if (node.right != null) {
q.offer(node.right);
}
}
}
return counter;
}
}
reference:
https://discuss.leetcode.com/topic/33826/two-java-iterative-solution-dfs-and-bfs
得把 tree 的三种遍历方式 iteration, recursion 都复习一遍。
Anyway, Good luck, Richardo! 08/28/2016