My C# one stack


  • 0
    R
    public IList<int> PostorderTraversal(TreeNode root) {
            IList<int> res = new List<int>();
            if (root == null) return res;
            Stack<TreeNode> stk = new Stack<TreeNode>();
            stk.Push(root);
            while(stk.Any())
            {
                TreeNode c= stk.Pop();
                if (c.right == null && c.left == null)
                {
                   res.Add(c.val);
                }else
                {
                    TreeNode l = c.left;
                    TreeNode r = c.right;
                    c.right = null;
                    c.left= null;
                    stk.Push(c);
                    if (r  != null) stk.Push(r);
                    if (l != null) stk.Push(l);
                }
            }
    
            return res;
        }
    

Log in to reply
 

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