Recursion:
1 PackageThe sword refers to an offer . Pre-sequence traversal;2 3 Importjava.util.ArrayList;4 5 /**6 * Created by Nick on 2018/10/6.7 */8 Public classSolution {9Arraylist<integer> res=NewArraylist<integer>();Ten Public voidPrenode (TreeNode root) { One if(root==NULL) A return; - Res.add (root.val); - Prenode (root.left); the Prenode (root.right); - } - - } + classTreeNode { - intval = 0; +TreeNode left =NULL; ATreeNode right =NULL; at - PublicTreeNode (intval) { - This. val =Val; - - } -}
Non-recursive:
1 PackageThe sword refers to an offer . Pre-sequence traversal;2 3 Importjava.util.ArrayList;4 ImportJava.util.Stack;5 6 /**7 * Created by Nick on 2018/10/6.8 */9 Public classSolution1 {TenArraylist<integer> res=NewArraylist<integer>(); One PublicArraylist<integer>Prenode (TreeNode root) { AStack<treenode> temp=NewStack<treenode>(); - if(root==NULL) - returnRes; the Temp.push (root); - while(!Temp.isempty ()) { -TreeNode t=Temp.pop (); - Res.add (t.val); + if(t.right!=NULL) - Temp.push (root.right); + if(t.left!=NULL) A Temp.push (root.left); at - } - returnRes; - } - - Public Static voidMain (string[] args) { inTreeNode root=NewTreeNode (1); -root.left=NewTreeNode (2); toroot.right=NewTreeNode (3); + -System.out.println (NewSolution1 (). Prenode (root)); the } *}
Pre-sequence traversal (recursive, non-recursive)