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