LeetCode 144. Binary Tree Preorder Traversal solution report

Source: Internet
Author: User

LeetCode 144. Binary Tree Preorder Traversal solution report
144. Binary Tree Preorder TraversalMy SubmissionsQuestionTotal Accepted: 108336 Total Submissions: 278322 Difficulty: Medium

Given a binary tree, return thepreordertraversal of its nodes 'values.

For example:
Given binary tree{1,#,2,3},

   1    \     2    /   3

Return[1,2,3].

Note: Recursive solution is trivial, cocould you do it iteratively?

Subscribeto see which companies asked this question

Show TagsShow Similar ProblemsHave you met this question in a real interview? YesNo

Returns the first root traversal order of a binary tree. The recursive solution is very simple. Can it be solved in a non-recursive way.

When traversing a node, the right child is added to the stack. Search left until it is empty.

My AC code

public class BinaryTreePreorderTraversal {public List
 
   preorderTraversal(TreeNode root) {        List
  
    list = new ArrayList
   
    ();        Stack
    
      stack = new Stack
     
      ();        TreeNode cur = root;        while (cur != null || !stack.isEmpty()) {while (cur != null) {list.add(cur.val);if(cur.right != null) stack.add(cur.right);cur = cur.left;}if(!stack.isEmpty()) cur = stack.pop();}        return list;    }}
     
    
   
  
 

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.