LeetCode-热题100-笔记-day29

199. 二叉树的右视图icon-default.png?t=N7T8https://leetcode.cn/problems/binary-tree-right-side-view/

给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

示例 1:

输入: [1,2,3,null,5,null,4]
输出: [1,3,4]

算法思路

使用层次遍历按层输出该二叉树并保存于临时数组cur中,然后遍历cur获取每一层最后一个元素添加大ans即可得到答案;

class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> ans=new ArrayList<>();
        List<List<Integer>> cur=new ArrayList<List<Integer>>();
        if(root==null){
          return ans;
        }
        Queue<TreeNode> queue=new ArrayDeque<>();
        queue.offer(root);
        while(!queue.isEmpty()){
          List<Integer> level=new ArrayList<>();
          int size=queue.size();
          for(int i=0;i<size;i++){
            TreeNode tmp=queue.poll();
            if(tmp.left!=null){
              queue.offer(tmp.left);
            }
            if(tmp.right!=null){
              queue.offer(tmp.right);
            }
            level.add(tmp.val);
          }
          cur.add(level);
        }
        for(List<Integer> innerList:cur){
          if (!innerList.isEmpty()) { // 检查子列表是否非空
          Integer element = innerList.get(innerList.size()-1); // 获取子列表的最后一个元素
          ans.add(element);
          }
        }
        return ans;
    }
}

 

230. 二叉搜索树中第K小的元素icon-default.png?t=N7T8https://leetcode.cn/problems/kth-smallest-element-in-a-bst/

给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

示例 1:

输入:root = [3,1,4,null,2], k = 1
输出:1

算法思路

中序遍历可得到顺序的二叉树元素;将遍历结果存储到列表中访问第K个元素即可; 

class Solution {
    List<Integer> ans=new ArrayList<>();
    public int kthSmallest(TreeNode root, int k) {
        dfs(root);
        return ans.get(k-1);
    }

    public void dfs(TreeNode root){
        if(root==null){
            return;
        }
        dfs(root.left);
        ans.add(root.val);
        dfs(root.right);
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值