LeetCode算法题–二叉树的最大深度
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
返回它的最大深度 3 。
题目思路:
迭代每个节点,将节点弹出栈,并且每次更新最大深度。
/**
* 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<Pair<TreeNode, Integer>> stack = new LinkedList<>();
stack.add(new Pair(root, 1));
int depth = 0;
while(!stack.isEmpty()){
Pair<TreeNode, Integer> current = stack.poll();
root = current.getKey();
int currentDepth = current.getValue();
if(root != null){
depth = currentDepth;//官方用了Max(cuurentDepth,depth),我认为不必,因为迭代到最后的节点一定是最大深度的节点。
stack.add(new Pair(root.left, currentDepth + 1));
stack.add(new Pair(root.right, currentDepth + 1));
}
}
return depth;
}
}
执行结果:
java中Pair的使用:
当一个函数返回两个值并且两个值都有重要意义时我们一般会用Map的key和value来表达,但是这样的话就需要两个键值对,用Map映射去做处理时,此时的key相当于value的一个描述或者引用,而具体的信息都保存在value中,我们可以通过key去获取对应的value。但是当key和value都保存具体信息时,我们就需要用到Pair对了。Pair对也是键值对的形式。
具体的实现:
1.在javax.util包下,有一个简单Pair类可以直接调用,用法是直接通过构造函数将所吸引类型的Key和value存入,这个key和value没有任何的对应关系类型也是任意定的。
用法:
Pair<String, String> pair = new Pair<>(“aku”, “female”);
pair.getKey();
pair.getValue();