首页 > 编程语言 >【hot100-java】二叉树的右视图

【hot100-java】二叉树的右视图

时间:2024-10-11 13:49:15浏览次数:9  
标签:right TreeNode val 视图 二叉树 java left root ret

二叉树篇

tql

 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
         List<Integer> ret=new ArrayList<>();
         dfs(root,0,ret);
         return ret;
    }

    private void dfs(TreeNode root,int depth,List<Integer>ret){
        if(root==null){
            return;
        }
        //这个深度首次达到
        if(depth==ret.size()){
              ret.add(root.val);
        }
        //先递归右子树,再递归左子树
        dfs(root.right,depth+1,ret);
        dfs(root.left,depth+1,ret);
    }
}

标签:right,TreeNode,val,视图,二叉树,java,left,root,ret
From: https://blog.csdn.net/m0_73629042/article/details/142851685

相关文章