LeetCode 145:Binary Tree Postorder Traversal

Posted cxchanpin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 145: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 you do it iteratively?

Subscribe to see which companies asked this question

 //利用两个栈s1和s2实现二叉树的后序遍历
 //1.申请一个栈s1,然后将头节点root压入s1中;
 //2.从s1中弹出的节点记为p,然后依次将p的左孩子和右孩子(不为空的话)压入s1中;
 //3.整个过程中。每个从s1中弹出的节点都放入s2中;
 //4.不断反复步骤2和步骤3,直到s1为空,过程结束。
 //5.最后,从s2中依次弹出节点就可以。

//每棵子树的头节点都是最先从s1中弹出,然后把该节点的孩子节点依照先左再右的顺序压入s1中,那么从s1弹出的顺序就是先右再左 //所以从s1中弹出的顺序就是根、右、左,然后。s2又一次弹出的顺序就变成了左、右、根。 class Solution { public: vector<int> postorderTraversal(TreeNode* root) { stack<TreeNode*> s1; stack<TreeNode*> s2; vector<int> res; if (root == NULL) return res; TreeNode* p = root; s1.push(root); while (!s1.empty()) { p=s1.top(); s1.pop(); s2.push(p); if (p->left != NULL) s1.push(p->left); if (p->right != NULL) s1.push(p->right); } while (!s2.empty()) { p = s2.top(); res.push_back(p->val); s2.pop(); } return res; } };


技术分享





以上是关于LeetCode 145:Binary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

leetcode 145. Binary Tree Postorder Traversal

LeetCode 145:Binary Tree Postorder Traversal

leetcode145. Binary Tree Postorder Traversal

LeetCode 145: Binary Tree Postorder Traversal

leetcode No145. Binary Tree Postorder Traversal

LeetCode OJ 145. Binary Tree Postorder Traversal