Pre-sequence traversal (recursive, non-recursive)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.