【每日算法】二叉树 找树左下角的值

目录

层序遍历

递归遍历

递归不揍

递归总代码



513.找树左下角的值

层序遍历

找树的最底层,最先想到的是层序遍历。我们只需要记录一层的第一个节点,然后遍历到下一层时,就覆盖这个值,怎样就可以保证我们记录的是最后一层的节点了。

下面是迭代层序遍历

 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;
    }

递归遍历

这道题用层序遍历会更简单,用递归的话,就会难一点。

寻找左下角的值,可能第一反应是一直遍历左节点,当遍历到叶子节点的时候,就返回这个节点的值,但是其实这是错误的,我们来看一下下面这个情况

如果这样的话,得到的就不是我们要求的值了。

这里我们应该求节点的最大深度,当深度最大时,将节点保存下来。

递归不揍

  1. 确定函数返回值和参数

参数是给定的树,返回值就是void

 private void findLeftValue(TreeNode root, int depth) {}
  1. 确定递归结束条件

当遍历到根节点时,就返回,同时,如果这个节点的深度比记录的最大深度大的话,就将这个节点的值记录下来,同时最大深度更新

 if (root.left == null && root.right == null){
            if (depth > maxDepth){
                maxDepth = depth;
                res = root.val;
            }
            return;
        }
  1. 确定递归遍历顺序

如果左节点不为空,就遍历左节点,如果右节点不为空,就遍历右节点

 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 --;
        }

        
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值