[Leedcode 145] Binary Tree postorder Traversal

Source: Internet
Author: User

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] .

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicList<integer>postordertraversal (TreeNode root) {//The post-order traversal and the middle sequence traversal are different because the root node needs to be accessed after the left and right nodes, so when you save the record, you need to determine whether a node is a leaf node, and//if his child has traversed, use Mark to mark it, indicating that the child has traversed. Note the order in which the child nodes are added to the stack, push the right node first, and then push the child nodelist<integer>res=NewArraylist<integer>(); if(root==NULL)returnRes; Stack<TreeNode> stack=NewStack<treenode>();        Stack.push (root); TreeNode Mark=root;//represents a node that has already been visited         while(!Stack.isempty ()) {TreeNode node=Stack.peek (); if(node.left==NULL&&node.right==NULL|| node.left==mark| | node.right==Mark)                {Res.add (node.val); Mark=node;            Stack.pop (); }Else{                if(node.right!=NULL){//////OrderStack.push (node.right); }                if(node.left!=NULL) {Stack.push (node.left); }            }        }          returnRes; }   /*list<integer> Res;        Public list<integer> postordertraversal (TreeNode root) {res=new arraylist<integer> ();        if (root==null) return res;        Getres (root);    return res;        public void Getres (TreeNode root) {if (root==null) return;        Getres (Root.left);        Getres (Root.right);    Res.add (Root.val); }*/}

[Leedcode 145] Binary Tree postorder Traversal

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.