145. Binary Tree Postorder Traversal
来源:互联网 发布:淘宝购物车图片及价格 编辑:程序博客网 时间:2024/06/11 05:31
/*Given a binary tree, return the postorder traversal of its nodes' values.For example:Given binary tree {1,#,2,3}, 1 \ 2 / 3return [3,2,1].Note: Recursive solution is trivial, could you do it iteratively?使用迭代实现二叉树的后序遍历*//** * 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) { vector<int> res; stack<TreeNode*> st; TreeNode* lastVisit=NULL; TreeNode* ptr=root; while(ptr || !st.empty()) { if(ptr) { st.push(ptr); ptr=ptr->left; } else { TreeNode* topNode=st.top(); if(topNode->right && topNode->right!=lastVisit) ptr=topNode->right; else { res.push_back(topNode->val); lastVisit=topNode; st.pop(); } } } return res; } vector<int> postorderTraversal2(TreeNode* root) { vector<int> res; stack<TreeNode*> st; if(root) st.push(root); while(!st.empty()) { TreeNode* topNode=st.top(); st.pop(); res.push_back(topNode->val); if(topNode->left) st.push(topNode->left); if(topNode->right) st.push(topNode->right); } reverse(res.begin(),res.end()); return res; }};
阅读全文
0 0
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145.Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 145. Binary Tree Postorder Traversal
- 《三体》里的超级计算机_我们今天能造出来吗?
- Linux IO模式及 select、poll、epoll详解
- C primer plus 9.1.1打印信头程序
- 布局处于键盘之上以及艾特功能
- CSS教程-如何创建CSS
- 145. Binary Tree Postorder Traversal
- TensorFlow基本概念
- andorid状态机StateMachine
- BufferReader类举一反三
- 岭回归中GCV,HKB,L-W的解释
- Android开发中一些被冷落但却很有用的类和方法
- 面试题13.在O(1)时间删除链表节点
- leetcode 68. Text Justification 文本对齐
- 基于卷积的密度统计(一)密度图的生成