前言
保持树堆递归的敏感性,在递归回溯的过程来完成其它操作。
一、DFS
通过递归找到叶子节点,来判断深度是否为最大深度。
1、源码
int max = Integer.MIN_VALUE;
public int maxDepth(TreeNode root) {
if (root == null)
return 0;
dfs(root, 1);
return max;
}
public void dfs(TreeNode root, int deepth) {
if (root.left == null && root.right == null) {
max = max < deepth ? deepth : max;
return;
}
if (root.left != null)
dfs(root.left, deepth + 1);
if (root.right != null)
dfs(root.right, deepth + 1);
}
二、回溯时计数
上面的方法是在递归下去的时候就计好数了,遇到叶子节点去比较。而可以在回溯的时候计数,遇到叶子节点才放回并加上自己(+1).
1、源码
public int maxDepth(TreeNode root) {
return root != null ? Math.max(maxDepth(root.left), maxDepth(root.right)) + 1 : 0;
}
总结
保持树对递归的敏感性,可以利用递归中做事情,也可以利用回溯的时候做事情,也可以剪枝来减少运算时间。