代码随想录算法训练营第16天 | 二叉树更加进阶

2024年7月18日

用层序遍历巧解
题513. 找树左下角的值
层序遍历的板子一定要熟背。

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        //用根左右遍历,每次记录高度
        int height=0;
        res = digui(res,height,root);
        return res.get(res.size()-1).get(0);
    }

    public List<List<Integer>> digui(List<List<Integer>> res,int height,TreeNode p){
        if(res.size()<height+1){
            List<Integer> res1 = new ArrayList<>();
            res.add(res1);
        }
        int val = p.val;
        res.get(height).add(val);
        if(p.left!=null){
            res = digui(res,height+1,p.left);
        }
        if(p.right!=null){
            res = digui(res,height+1,p.right);
        }
        return res;
    }
}
posted @   hailicy  阅读(5)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端
点击右上角即可分享
微信分享提示