Binary Tree Postorder Traversal

Source: Internet
Author: User

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, cocould you do it iteratively?

Method
/*** Ensure that the root node can be accessed only after the access from the left and right children. Therefore, for any node P, first import it into the stack. * If P does not have a left or right child, you can directly access it. Or P has a left or right child, but both the left and right children have been accessed, you can also directly access this node. * If the preceding two conditions are not met, P's right child and left child are added to the stack in sequence. * This ensures that each time the top element of the stack is taken, the left child is accessed in front of the right child, and the left child and the Right child are accessed in front of the root node. */Private Stack
 
  
Stack = new Stack
  
   
(); Public ArrayList
   
    
PostorderTraversal (TreeNode root) {ArrayList
    
     
Al = new ArrayList
     
      
(); If (root! = Null) {TreeNode cur = null; TreeNode pre = null; stack. push (root); while (stack. size ()! = 0) {cur = stack. peek (); if (cur. left = null & cur. right = null) | (pre! = Null & (pre = cur. left | pre = cur. right) {al. add (cur. val); pre = cur; stack. pop ();} else {if (cur. right! = Null) {stack. push (cur. right);} if (cur. left! = Null) {stack. push (cur. left) ;}}} return al ;}
     
    
   
  
 


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.