ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

LeetCode [中等]二叉树的右视图(层序

2026/9/11 1:07:32 拓冰建站 浏览量
LeetCode [中等]二叉树的右视图(层序

199. 二叉树的右视图 - 力扣(LeetCode)

从二叉树的层序遍历改进,根右左

/*** Definition for a binary tree node.* public class TreeNode {*     public int val;*     public TreeNode left;*     public TreeNode right;*     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
public class Solution {public List<int> res = new List<int>();public IList<int> RightSideView(TreeNode root) {if(root == null)return res.ToArray();DFS(root,0);return res.ToArray();}private void DFS(TreeNode root, int level){if(root == null)return;if(res.Count < level + 1){res.Add(root.val);}DFS(root.right, level + 1);DFS(root.left, level + 1);}}