一般来说有两种方案,一种是采用递归的方式,另一种是采用循环迭代的方式模拟递归的栈。
递归方式:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftDep = maxDepth(root.left);
int rightDep = maxDepth(root.right);
return Math.max(leftDep, rightDep) + 1;
}
}
迭代方式:首先得有一个栈存node,可是node的深度信息没有,也得存下来,要不然没法计算。所以需要两个栈
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Stack<TreeNode> nodeStack = new Stack();
Stack<Integer> depthStack = new Stack();
nodeStack.push(root);
depthStack.push(1);
int depth = 0, currentDepth = 0;
while(!nodeStack.empty()) {
root = nodeStack.pop();
currentDepth = depthStack.pop();
depth = Math.max(depth, currentDepth);
if (root.right != null) {
nodeStack.push(root.right);
depthStack.push(currentDepth + 1);
}
if (root.left != null) {
nodeStack.push(root.left);
depthStack.push(currentDepth + 1);
}
}
return depth;
}
}
采用广度优先遍历的解法:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> queue = new LinkedList();
queue.offer(root);
int maxDepth = 0;
while (!queue.isEmpty()) {
++maxDepth;
int length = queue.size();
for (int i = 0; i < length; i++) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
}
return maxDepth;
}
}