C# - iterative DFS


  • 0
        public IList<int> LargestValues(TreeNode root) 
        {
            Stack<TreeNode> nodeStack = new Stack<TreeNode>();
            Stack<int> levelStack = new Stack<int>();
            TreeNode curr = root;
            int level = 0;
            
            IList<int> vals = new List<int>();
            while (curr != null || nodeStack.Count > 0)
            {
                if (curr != null)
                {
                    if (vals.Count <= level) vals.Add(curr.val);
                    nodeStack.Push(curr);
                    levelStack.Push(level);
                    curr = curr.left;
                    level++;
                }
                else
                {
                    curr = nodeStack.Pop();
                    level = levelStack.Pop();
                    
                    // visit
                    if (curr.val > vals[level]) vals[level] = curr.val;
                    
                    curr = curr.right;
                    level++;
                }
            }
            return vals;
        }
    

Log in to reply
 

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