C# solution using two stacks


  • 0
    C
    public List<int> PostorderTraversal(TreeNode root) {
            Stack<TreeNode> s1=new Stack<TreeNode>();
            Stack<TreeNode> s2=new Stack<TreeNode>();
            List<int> res = new List<int>();
            if(root!=null)
                s1.Push(root);
            while(s1.Count>0){
                TreeNode node = s1.Pop();
                s2.Push(node);
                
                if(node.left!=null)
                    s1.Push(node.left);
                if(node.right!=null)
                    s1.Push(node.right);
            }
            
            while(s2.Count>0){
                res.Add(s2.Pop().val);
            }
            return res;    
        }
    

Log in to reply
 

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