[leetcode]144 Binary Tree Preorder traversal

Source: Internet
Author: User

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

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.