"144-binary Tree Preorder Traversal (binary tree non-recursive pre-sequence traversal)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
Given a binary tree, return the preorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3}
,
1 2 / 3
Return [1,2,3]
.
Note:recursive solution is trivial, could do it iteratively?
Main Topic
Given a binary tree, output the results of the pre-order traversal, and try to use two methods to implement
Thinking of solving problems
The first: use recursion.
The second type: Using non-recursive methods
Code Implementation
Node class
publicclass TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; }}
The first method: the implementation class of the algorithm
ImportJava.util.LinkedList;ImportJava.util.List; Public class solution { Privatelist<integer> result; PublicList<integer>Preordertraversal(TreeNode Root) {result =NewLinkedlist<> (); Preorder (root);returnResult }Private void Preorder(TreeNode Root) {if(Root! =NULL) {Result.add (root.val); Preorder (Root.left); Preorder (root.right); } }}
The second method: the implementation class of the algorithm
PublicClass Solution { Public List<Integer>Preordertraversal (TreeNode root) {List<Integer>Result= NewLinkedList<>();if(Root!= NULL) {Deque<TreeNode> Stack = NewLinkedList<>();Stack.Add (root); while(!Stack.IsEmpty ()) {TreeNode node= Stack.Removelast (); Result.Add (node.Val);if(node.Right!= NULL) {Stack.Add (node.right); }if(node.Left!= NULL) {Stack.Add (node.left); } } }returnResult }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
The result of the first method:
The result of the first method:
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47774643"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "144-binary Tree Preorder Traversal (binary non-recursive pre-sequence traversal)"