https://oj.leetcode.com/problems/binary-tree-preorder-traversal/
http://blog.csdn.net/linhuanmars/article/details/21428647
/** * definition for binary tree * public class treenode { * int val; * TreeNode left; * treenode right; * treenode (int &NBSP;X) { val = x; } * } */public class solution { public list<integer> preordertraversal (TreeNode root) { // Solution a: // return preordertraversal_ Recursion (Root); // solution b: return preordertraversal_ iteration (root); &NBSP;&NBSP;&NBSP;&NBSP;}&NBSP;&Nbsp; ///////////////////// // solution a: recursion // private list<integer> preordertraversal_recursion ( Treenode root) { list<integer > result = new ArrayList<> (); Visit (Root, result); return result; } private void visit (TreeNode node, List<integer> result) { if (Node == null) return; result.add (node.val); visit (Node.left, result); visit (Node.right, result); } ///////////////////// // Solution A: Iteration // private list<integer> preordertraversal_iteration ( Treenode root) { list<integer > result = new ArrayList<> (); if (root == null) return result; Stack<TreeNode> stack = new stack&lT;> (); stack.push (Root); while (!stack.empty ()) { Treenode node = stack.pop (); result.add (Node.val); // Put right first if (node.right != null) stack.push (node.right); if ( Node.left != null) stack.push (Node.left); } return result; }}
[leetcode]144 Binary Tree Preorder traversal