//DFS: 后序 Post-order Traversal, Stack public List<int> PostOrderTraversal_Iterative1(TreeNode root) { //Postorder traversal is more complicated to implement comparing to Preorder and Inorder. //At what point shall we visit the root node: //Condition 1: The root node has no child at all. //Condition 2: The root's child has already been visited. List<int> result = new List<int>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if (root != null) stack.Push(root); TreeNode prev = null; while (stack.Count != 0) { root = stack.Peek(); bool noChild = (root.left == null && root.right == null); bool doneChild = false; if (prev != null && (prev == root.left || prev == root.right)) doneChild = true; //直到没有child了或者child已经访问完了才把栈顶元素出栈 if (noChild || doneChild) { root = stack.Pop(); result.Add(root.val); prev = root; } else { if (root.right != null) stack.Push(root.right); if (root.left != null) stack.Push(root.left); } } return result; }
public int solution(string S) { int minInteger = 0; int maxInteger = (1 << 20) - 1; Stack<int> stack = new Stack<int>(); foreach (string op in S.Split(' ')) { if (op == "DUP") { if (!stack.Any()) { return -1; } stack.Push(stack.Peek()); } else if (op == "POP") { if (!stack.Any()) { return -1; } stack.Pop(); } else if (op == "+") { if (stack.Count() < 2) { return -1; } var top = stack.Pop(); var nextTop = stack.Pop(); var sum = top + nextTop; if (sum > maxInteger) { // Overflow return -1; } stack.Push(sum); } else if (op == "-") { if (stack.Count() < 2) { return -1; } var top = stack.Pop(); var nextTop = stack.Pop(); var diff = top - nextTop; if (diff < minInteger) { // Overflow return -1; } stack.Push(diff); } else { int number; if (!int.TryParse(op, out number)) { return -1; } if (number < minInteger || number > maxInteger) { return -1; } stack.Push(number); } } if (!stack.Any()) { return -1; } return stack.Pop(); }