"Leetcode-Interview algorithm classic-java implementation" "145-binary Tree postorder Traversal (binary trees non-recursive sequential traversal)"

Source: Internet
Author: User
Tags prev

"145-binary Tree postorder Traversal (binary tree non-recursive post-traversal)" "leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index" Original Question

Given a binary tree, return the postorder traversal of its nodes ' values.
For example:
Given binary Tree {1,#,2,3} ,

   1         2    /   3

Return [3,2,1] .
Note:recursive solution is trivial, could do it iteratively?

Main Topic

Given a binary tree, output sequential traversal results, try to use two methods to implement

Thinking of solving problems

The first: use recursion.
The second type: Using non-recursive methods
According to the order of sequential traversal, first access to the left subtree, and then access to the right subtree, and then access the root node, and for each subtree, and follow the same access sequence to traverse, post-order traversal of the non-recursive implementation is relatively difficult to ensure that the root node in the Saozi right subtree is accessed before access, the idea is as follows:
For either node p,
1) the node p into the stack first;
2) If p does not exist left child and right child, or p exists left child or right child, but the child has been output, you can directly output node p, and will be out of the stack, the stack node p is marked as the last output node, and then the top node of the stack at this point is set to the current nodes;
3) If the condition in 2 is not satisfied, then the right child and the left child of P are sequentially put into the stack, the current node is reset to the top node of the stack, and then repeated Operation 2);
4) until the stack is empty, the traversal ends.

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>Postordertraversal(TreeNode Root) {result =NewLinkedlist<> (); Preorder (root);returnResult }Private void Preorder(TreeNode Root) {if(Root! =NULL) {preorder (root.left);            Preorder (root.right);        Result.add (Root.val); }    }}

The second method: the implementation class of the algorithm

ImportJava.Util.Deque;ImportJava.Util.LinkedList;ImportJava.Util.List; PublicClass Solution { Public List<Integer>Postordertraversal (TreeNode root) {List<Integer> List = NewLinkedList<>();if(Root!= NULL) {//Double-ended queue, as a stack to useDeque<TreeNode>Deque= NewLinkedList<>();//point to the previous processing nodeTreeNode prev= NULL;//points to the currently processed nodeTreeNode Curr;//root node into the stackDeque.AddLast (root);//stack non-empty             while(!Deque.IsEmpty ()) {//Get stack top element (not deleted)Curr=Deque.GetLast ();if((Curr.Left== NULL &&Curr.Right== NULL)//Current element has no left or right subtree                        //prev! = null && Curr.left = = prev, the current node is only left dial hand tree, and the left subtree has traversed                        //prev! = null && Curr.right = = prev, the current node has left and right subtrees, and the left and right subtrees have traversed                        ||(prev!= NULL &&(Curr.Left==Prev||Curr.Right==prev)) {//delete top of stack elementCurr=Deque.Removelast ();//node value into the stack                    List.Add (Curr.Val);//Update the last processed nodePrev=Curr }Else{///left and right subtree not traversed, will be non-empty left and right subtree into the stack                    if(Curr.Right!= NULL) {Deque.AddLast (Curr.right); }if(Curr.Left!= NULL) {Deque.AddLast (Curr.left); }                }            }        }return List; }}
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/47774647"

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Leetcode-Interview algorithm classic-java implementation" "145-binary Tree postorder Traversal (binary trees non-recursive sequential traversal)"

Related Article

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.