LeetCode:145_Binary Tree Postorder Traversal | 二叉树后序遍历 | Hard

简介: 题目:Binary Tree Postorder Traversal 二叉树的后序遍历,题目要求是采用非递归的方式,这个在上数据结构的课时已经很清楚了,二叉树的非递归遍历不管采用何种方式,都需要用到栈结构作为中转,代码很简单,见下: 1 struct TreeNode { 2 ...

题目:Binary Tree Postorder Traversal

二叉树的后序遍历,题目要求是采用非递归的方式,这个在上数据结构的课时已经很清楚了,二叉树的非递归遍历不管采用何种方式,都需要用到栈结构作为中转,代码很简单,见下:

 1 struct TreeNode {
 2     int            val;
 3     TreeNode*    left;
 4     TreeNode*    right;
 5     TreeNode(int x): val(x), left(NULL),right(NULL) {}
 6 };
 7 
 8 vector<int> preorderTraversal(TreeNode *root) //非递归的后序遍历(用栈实现)
 9 {
10     if (NULL == root) {
11         return vector<int>();
12     }
13     
14     stack<TreeNode *> tree_stack;
15     vector<int> tree_vector;
16 
17     tree_stack.push(root);
18     TreeNode *p = NULL;
19     while (!tree_stack.empty()) {
20         TreeNode *pTemp = tree_stack.top();
21         if ((pTemp->left == NULL && pTemp->right == NULL) || ((p != NULL) && (pTemp->left == p || pTemp->right == p))) {
22             tree_vector.push_back(pTemp->val);
23             tree_stack.pop();
24             
25             p = pTemp;
26         }
27         else {
28             while(pTemp) {
29                 if (pTemp->right != NULL) 
30                     tree_stack.push(pTemp->right);
31 
32                 if (pTemp->left != NULL)
33                     tree_stack.push(pTemp->left);
34                 pTemp = pTemp->left;
35             }
36         }
37     }
38     return tree_vector;
39 }

 

目录
相关文章
|
6天前
|
算法 DataX
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
二叉树(中)+Leetcode每日一题——“数据结构与算法”“剑指Offer55-I. 二叉树的深度”“100.相同的树”“965.单值二叉树”
|
8天前
|
算法
【力扣】94. 二叉树的中序遍历、144. 二叉树的前序遍历、145. 二叉树的后序遍历
【力扣】94. 二叉树的中序遍历、144. 二叉树的前序遍历、145. 二叉树的后序遍历
|
1月前
leetcode热题100.二叉树中的最大路径和
leetcode热题100.二叉树中的最大路径和
18 0
|
26天前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
1月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记
|
1月前
|
搜索推荐
《LeetCode》——LeetCode刷题日记3
《LeetCode》——LeetCode刷题日记3
|
1月前
|
容器
《LeetCode》——LeetCode刷题日记1
《LeetCode》——LeetCode刷题日记1
|
1月前
|
算法
LeetCode刷题---21.合并两个有序链表(双指针)
LeetCode刷题---21.合并两个有序链表(双指针)
|
1月前
|
算法 测试技术
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
LeetCode刷题--- 430. 扁平化多级双向链表(深度优先搜索)
|
1月前
|
存储
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
实现单链表的基本操作(力扣、牛客刷题的基础&笔试题常客)
143 38

热门文章

最新文章