Leetcode:binary Tree postorder Traversal Problem Solving report

Source: Internet
Author: User

Binary Tree postorder Traversal

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?

Show Tags
Has you met this question in a real interview? Yes No
Discuss

Solution 1:

Recursive solution

1  PublicList<integer>postorderTraversal1 (TreeNode root) {2list<integer> ret =NewArraylist<integer>();3 Dfs (root, ret);4         returnret;5     }6     7     //Solution 1:rec8      Public voidDFS (TreeNode root, list<integer>ret) {9         if(Root = =NULL) {Ten             return; One         } A          - Dfs (Root.left, ret); - Dfs (root.right, ret); the Ret.add (root.val); -}
View Code

Solution 2:

/**
* Sequential Traversal iterative method
* Http://www.youtube.com/watch?v=hv-mJUs5mvU
* http://blog.csdn.net/tang_jin2015/article/details/8545457
* Sequence from left to right is the same as the reverse order from right to left, so it's easy! Ha ha
* Flip with another stack
*/

1 //Solution 2:iterator2      PublicList<integer>postordertraversal (TreeNode root) {3list<integer> ret =NewArraylist<integer>();4         if(Root = =NULL) {5             returnret;6         }7         8stack<treenode> s =NewStack<treenode>();9Stack<integer> out =NewStack<integer>();Ten          One S.push (root); A          -          while(!S.isempty ()) { -TreeNode cur =S.pop (); the Out.push (cur.val); -              -             if(Cur.left! =NULL) { - S.push (cur.left); +             } -              +             if(Cur.right! =NULL) { A S.push (cur.right); at             } -         } -          -          while(!Out.isempty ()) { - Ret.add (Out.pop ()); -         } in          -         returnret; to}
View Code

GITHUB:

Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/PostorderTraversal.java

Leetcode:binary Tree postorder Traversal Problem Solving report

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.