LC145 Binary Tree Postorder Traversal
这个题比前序遍历难在,当tmp等于NULL时,stack需要不断地弹出节点,直到检查到一个节点,它的右节点不为空而且还没有被遍历过。这个判断条件写出来还是比较难。
当然,另一种巧妙的做法是,用前序遍历(按右根左的顺序)来求得数组,然后把数组做一个翻转就行。
1 class Solution { 2 public: 3 vector<int> postorderTraversal(TreeNode* root) { 4 vector<int> result; 5 if(root==NULL) 6 return result; 7 stack<TreeNode*> is; 8 is.push(root); 9 TreeNode* tmp = root->left; 10 TreeNode* pre=NULL; 11 while(!is.empty()||tmp!=NULL) 12 { 13 if(tmp) 14 { 15 is.push(tmp); 16 tmp=tmp->left; 17 } 18 else 19 { 20 while(!is.empty()&&(is.top()->right==NULL||is.top()->right==tmp)) 21 { 22 tmp=is.top(); 23 result.push_back(tmp->val); 24 is.pop(); 25 } 26 if(!is.empty()) 27 tmp=is.top()->right; 28 else 29 return result; 30 } 31 } 32 return result; 33 } 34 };
转载于:https://www.cnblogs.com/vaecn/p/5713519.html
LC145 Binary Tree Postorder Traversal相关推荐
- 5. Binary Tree Postorder Traversal
Binary Tree Postorder Traversal Given a binary tree, return the postorder traversal of its nodes' va ...
- 【二叉树的迭代版后序遍历】LeetCode 145. Binary Tree Postorder Traversal
LeetCode 145. Binary Tree Postorder Traversal Solution1:递归版答案 二叉树的后序遍历递归版是很简单的,关键是迭代版的代码既难理解又难写!但听了花 ...
- [LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历
Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary ...
- LeetCode 145. Binary Tree Postorder Traversal
原题链接在这里:https://leetcode.com/problems/binary-tree-postorder-traversal/ 题目: Given a binary tree, retu ...
- Binary Tree Postorder Traversal
https://leetcode.com/problems/binary-tree-postorder-traversal/ Given a binary tree, return the posto ...
- 145. Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values. For example: Given binary ...
- LeetCode:145. Binary Tree Postorder Traversal
总共想出了四种方法来做. 第一种是递归,不说了.后面集中都是迭代. 第二种是使用一个栈,而且借助一个set来记录哪些node是访问过它的子节点的,防止重复访问.缺点是需要额外的set的空间 class ...
- Leetcode 之Binary Tree Postorder Traversal(44)
后序遍历,比先序和中序都要复杂.访问一个结点前,需要先判断其右孩子是否被访问过.如果是,则可以访问该结点:否则,需要先处理右子树. vector<int> postorderTravers ...
- 145. Binary Tree Postorder Traversal 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历. 示例: 输入: [1,null,2,3] 1\2/3 输出: [3,2,1] 进阶: 递归算法很简单,你可以通过迭代算法完成吗? DFS 今天这道题比较简单,直 ...
最新文章
- python【蓝桥杯vip练习题库】ADV-150 周期字串
- BZOJ.3218.a + b Problem(最小割ISAP 可持久化线段树优化建图)
- mysql 子查询添加索引_mysql – 你能索引子查询吗?
- 技术系列课回顾 | 直播点播窄带高清之 JND 感知编码技术
- R语言paste函数
- Java 7#8:测试台上的NIO.2文件通道
- 【转载保存】网页提取正文算法汇总
- java注释 param_@Param注解的用法解析
- @程序员,除了女朋友你还要带什么回去?
- Docker应用基础
- Geodatabase模型
- oracle10g的系统视图(sys、system)
- SAP中多层扩展有效地bom
- 我是这样手写Spring的,麻雀虽小五脏俱全
- NUC980开源项目38-4g上网
- (1)定义圆Circle类,包含radius半径属性,求面积方法,求周长方法,返返回圆对象的详细信息的方法(2)在测试类中创建长度为5的Circle[]数组,用来装5个圆对象
- 【Map】Echarts之iphone销量地图的使用以及详细配置
- Kaggle: Tweet Sentiment Extraction 方法总结 Part 1/2: 常用方法总结
- 计算机有硬盘读不出来怎么办,电脑开机后读不到硬盘怎么办
- Netlogo 之获取邻居中距离当前海龟最近的海龟