LeetCode144 Binary Tree Preorder Traversal (iterative implementation) Java

Source: Internet
Author: User

Title:
Given a binary tree, return the preorder traversal of its nodes ' values.

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

   1         2    /   3

return [+].

Note:recursive solution is trivial, could do it iteratively?

Analysis:
First, the root traversal of the binary tree, that is, for each node in the two-tree, the first access to the node, and then access its left subtree, and finally access its right subtree. Iterate through the binary tree first, need to use the stack. The steps are as follows:
(1) Put the root node into the stack.
(2) Enter the loop. The top element of the stack is first popped, accessed, then the right subtree of the element is put into the stack, and the left subtree of the element is finally stacked. Left dial hand tree after the right subtree into the stack to ensure that the Zuozi before the right subtree is accessed.

Code:

 PackageGlobal Public  class TreeNode {     Public intVal PublicTreeNode left; PublicTreeNode right; Public TreeNode(intX) {val = x; }@Override     PublicStringtoString() {return "TreeNode [val="+ val +", left="+ Left +", right="+ Right +"]"; }}
 Packageleetcode144;ImportGlobal. TreeNode;ImportJava.util.LinkedList;ImportJava.util.List;/** * The rule for root traversal tree is this: For each node encountered, first access the node itself, and then the Zogen node. * @author liyuncong * * * * Public  class LeetCode144 {     PublicList<integer>Preordertraversal(TreeNode Root) {list<integer> result =NewLinkedlist<integer> ();if(Root = =NULL) {returnResult } linkedlist<treenode> stack =NewLinkedlist<treenode> (); Stack.push (root); while(!stack.isempty ()) {TreeNode top = Stack.pop ();if(Top! =NULL) {Result.add (top.val);                Stack.push (Top.right);            Stack.push (Top.left); }        }returnResult }}

LeetCode144 Binary Tree Preorder Traversal (iterative implementation) Java

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.