0
点赞
收藏
分享

微信扫一扫

什么是ElasticSearch?

mafa1993 2023-12-08 阅读 36

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


}
举报

相关推荐

0 条评论