C# iterative easy to understand solution


  • 0
    S
    public IList<int> PostorderTraversal(TreeNode root) {
        List<int> vals = new List<int>();
        
        if (root == null) {
            return vals;
        }
        
        Stack<TreeNode> s = new Stack<TreeNode>();
        HashSet<TreeNode> v = new HashSet<TreeNode>();
        s.Push(root);
        
        while (s.Count > 0) {
            TreeNode n = s.Peek();
            if (!v.Contains(n)) {
                v.Add(n);
                if (n.right != null) {
                    s.Push(n.right);
                }
                if (n.left != null) {
                    s.Push(n.left);
                }
                if (n.left == null && n.right == null) {
                    vals.Add(n.val);
                    s.Pop();
                }
            } else {
                vals.Add(n.val);
                s.Pop();
                
            }
        }
        return vals;
    }

Log in to reply
 

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