leetcode刷题随笔 1.0
最近刷题下来发现一个规律
public int minDepth(TreeNode root) {
if(root == null) {
return 0;
}
if(root.left == null && root.right == null) {
return 1;
}
int ans = Integer.MAX_VALUE;
if(root.left != null) {
ans = Math.min(minDepth(root.left), ans);
}
if(root.right != null) {
ans = Math.min(minDepth(root.right), ans);
}
return ans + 1;
}
这个是查询树的最小深度的题,用的是DFS,其实这种类似的树的递归操作,如果看代码看不明白,可以直接想假如root就只有一层,或者二层,然后这个代码就可以看做,先处理了根的左节点,然后是右节点,然后再把深度返回一下,不要一下子就想到很深的树结构,脑子容易乱。
最后补充一下,树的三种常见遍历
- 前序遍历:根左右 根在前,先访问根
- 中序遍历:左根右 根在中间访问
- 后序遍历:左右根 根在最后访问
左右的顺序默认不变,主要改变的就是访问根节点的次序。