二叉树的最大深度的解决,很简单的一道题。
比如一棵树如图所示:
3
5 6
2 4
7
①递归的思路 :H = 1+max((H-5),(H-6)) = 4
H-5 = 1+max((H-2),(H-4)) = 3
H-2 = 1+max((H-7),0) = 2
H-7 = 1+max(0,0) = 1
H-4 = 1+max(0,0) = 1
H-6 = 1+max(0,0) = 1
代码实现:
/**
* 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;
}else{
int left_height = maxDepth(root.left);
int right_height = maxDepth(root.right);
return java.lang.Math.max(left_height,right_height)+1;
}
}
}
②迭代的思路:
class Solution{
public int maxDepth(TreeNode root){
Queue<Pair<TreeNode,Integer>> stack = new LinkedList<>();
if(root != null){
stack.add(new Pair(root,1));
}
int depth = 0;
while(!stack.isEmpty()){
Pair<TreeNode,integer> current = stack.poll();
root = current.getKey();
int current_depth = current.getValue();
if(root != null){
depth = Math.max(depth, current_depth);
stack.add(new Pair(root.left,current_depth+1));
sttack.add(new Pair(root.right,current_depth+1));
}
}
}
}