目录
层序遍历
找树的最底层,最先想到的是层序遍历。我们只需要记录一层的第一个节点,然后遍历到下一层时,就覆盖这个值,怎样就可以保证我们记录的是最后一层的节点了。
下面是迭代层序遍历
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int res = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
if (i == 0) {
res = poll.val;
}
if (poll.left != null) {
queue.offer(poll.left);
}
if (poll.right != null) {
queue.offer(poll.right);
}
}
}
return res;
}
递归遍历
这道题用层序遍历会更简单,用递归的话,就会难一点。
寻找左下角的值,可能第一反应是一直遍历左节点,当遍历到叶子节点的时候,就返回这个节点的值,但是其实这是错误的,我们来看一下下面这个情况
如果这样的话,得到的就不是我们要求的值了。
这里我们应该求节点的最大深度,当深度最大时,将节点保存下来。
递归不揍
- 确定函数返回值和参数
参数是给定的树,返回值就是void
private void findLeftValue(TreeNode root, int depth) {}
- 确定递归结束条件
当遍历到根节点时,就返回,同时,如果这个节点的深度比记录的最大深度大的话,就将这个节点的值记录下来,同时最大深度更新
if (root.left == null && root.right == null){
if (depth > maxDepth){
maxDepth = depth;
res = root.val;
}
return;
}
- 确定递归遍历顺序
如果左节点不为空,就遍历左节点,如果右节点不为空,就遍历右节点
if (root.left != null){
depth ++;
findLeftValue(root.left,depth);
depth --;
}
if (root.right != null){
depth ++;
findLeftValue(root.right,depth);
depth --;
}
递归总代码
int res = 0;
int maxDepth = -1;
public int findBottomLeftValue(TreeNode root) {
res = root.val;
findLeftValue(root,0);
return res;
}
private void findLeftValue(TreeNode root, int depth) {
if (root.left == null && root.right == null){
if (depth > maxDepth){
maxDepth = depth;
res = root.val;
}
return;
}
if (root.left != null){
depth ++;
findLeftValue(root.left,depth);
depth --;
}
if (root.right != null){
depth ++;
findLeftValue(root.right,depth);
depth --;
}
}