Leetcode 145 binary Tree Postorder Traversal (subsequent traversal of binary trees) + (binary tree, iteration)

Source: Internet
Author: User

translation
给定一个二叉树,返回其后续遍历的节点的值。例如:给定二叉树为 {1#, 2, 3}   1         2    /   3返回 [321]备注:用递归是微不足道的,你可以用迭代来完成它吗?
Original
returntheofits nodes‘ values.For example:Given binary tree {1,#,2,3},   1         2    /   3return [3,2,1isit iteratively?
Analysis

Directly on the code ...

vector<int> postorderTraversal(TreeNode* root) {    if (root != NULL) {        postorderTraversal(root->left);        postorderTraversal(root->right);             v.push_back(root->val);    }    return v;}
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode (int x): Val (x), left (null), right (null) {}*};*/classSolution { Public: vector<int>VvoidPostordertraversaliter (TreeNode *root, Stack<TreeNode*>&AMP;STAC) {if(Root = NULL)return;BOOLHasleft = root->left! = NULL;BOOLHasright = root->right! = NULL; Stac.push (root);if(hasright) Stac.push (root->right);if(hasleft) Stac.push (root->left);if(!hasleft &&!hasright) v.push_back (root->val);if(Hasleft)            {root = Stac.top ();            Stac.pop ();        Postordertraversaliter (Root, Stac); }if(Hasright)            {root = Stac.top ();            Stac.pop ();        Postordertraversaliter (Root, Stac); }if(Hasleft | | hasright) v.push_back (Stac.top ()->val);    Stac.pop (); } vector<int>Postordertraversal (treenode* root) { Stack<TreeNode*>Stac Postordertraversaliter (Root, Stac);returnV }     };

There are two other similar topics:

Leetcode 94 binary Tree Inorder traversal (middle order traversal of binary trees) + (binary tree, iteration)
Leetcode 144 binary Tree preorder traversal (binary trees pre-sequence traversal) + (binary tree, iteration)

Leetcode 145 binary Tree Postorder Traversal (subsequent traversal of binary trees) + (binary tree, iteration)

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.