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 res = new List();
    public IList 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);
    }


}

你可能感兴趣的:(C#题解,leetcode,深度优先,算法)