C# Pre-Order Traversal (Beats 96%)

  • 0

    Pre-Order Traversal starts from the root and goes down 1 level at a time. We maintain the current row (depth) we're in as we're traversing the tree. We use that row as the index to the list, where the ith value is the max value of the ith row. The traversal will visit every node, so by the time its done, every node will be compared in each row.

     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
    public class Solution {
        public IList<int> LargestValues(TreeNode root) {
            IList<int> list = new List<int>();
            Helper(root, list, 0);
            return list;
        private void Helper(TreeNode node, IList<int> list, int row) {
            if(node == null){
            if (list.Count() <= row){
                list[row] = Math.Max(list[row], node.val);
            Helper(node.left, list, row + 1);
            Helper(node.right, list, row + 1);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.