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:
Paste_Image.png
簡(jiǎn)單題盏檐。。驶悟。為了完成今天5道題的目標(biāo)胡野,但是又刷不動(dòng)了,選了這道簡(jiǎn)單題痕鳍。
沒(méi)什么好分析的硫豆。
**
總結(jié): 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));
}
}
一行解決問(wèn)題。
fuck. 也就只能在簡(jiǎn)單題里面裝個(gè)逼了
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<TreeNode> st = new Stack<TreeNode>();
Stack<Integer> value = new Stack<Integer>();
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;
}
}
用兩個(gè)棧的方法很巧妙额获。同時(shí)暫存頭結(jié)點(diǎn)的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<TreeNode> q = new LinkedList<TreeNode>();
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 都復(fù)習(xí)一遍够庙。
Anyway, Good luck, Richardo! 08/28/2016