LeetCode145. Binary Tree Postorder Traversal(后序遍历)
程序员文章站
2022-05-18 19:39:03
...
145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?
题目:二叉树的后续遍历,递归的方式。
思路:Preorder, Inorder, and Postorder Iteratively Summarization
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
stack<TreeNode*> nodes;
vector<int> res;
while(root != nullptr || nodes.size()){
if(root != nullptr){
nodes.push(root);
res.push_back(root->val);
root = root->right;
}
else{
TreeNode* node = nodes.top();
nodes.pop();
root = node->left;
}
}
reverse(res.begin(), res.end());
return res;
}
};
下一篇: Pycharm搭建spark环境
推荐阅读
-
Binary Tree Postorder Traversal
-
LeetCode-102. Binary Tree Level Order Traversal(层次遍历保存)
-
数据结构与算法1:二叉树(binary_tree)的前、中、后序(深度优先)和广度优先遍历及python代码实现
-
Given a binary tree, return the postorder traversal of its nodes' values.非递归后续遍历
-
LeetCode(106)Construct Binary Tree from Inorder and Postorder Traversal
-
leetcode: binary-tree-postorder-traversal:后序遍历二叉树
-
binary-tree-postorder-traversal
-
145. Binary Tree Postorder Traversal
-
Binary Tree Postorder Traversal
-
中序遍历 94. Binary Tree Inorder Traversal