【leetcode】binary-tree-postorder-traversal
来源:互联网 发布:爱丁堡商学院申请 知乎 编辑:程序博客网 时间:2024/06/10 15:19
题目:
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?
非递归实现二叉树的后序遍历 ,使用栈保存好每次的根节点就好了 .。。
遍历需要注意的地方就是:判断当前的结点的 子树有没有访问完
代码分析:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ #include<stack>//后序遍历二叉树class Solution {public: vector<int> postorderTraversal(TreeNode *root) { vector<int> ret; stack<TreeNode*> data; TreeNode* prev = NULL; if(root == NULL) return ret; while(data.empty() == false||root) { while(root) { data.push(root); root = root->left; } root = data.top();//用来判断当前的结点的右结点有没有遍历过 if(root->right == NULL||(root->right == prev)) { ret.push_back(root->val); prev = root; data.pop(); root = NULL; } else { root = root->right; } } return ret; }};
代码解析:
1、
if(root->right == NULL||(root->right == prev))这句代码使用的,使用的很是巧,
当前结点的有孩子为空 ,或者是当前结点右孩子已经被访问过了。才能访问当前的结点
2、
stack<TreeNode*> data;
使用栈来保存前面没有访问的结点;3、
TreeNode* prev = NULL;使用prev来保存的是上一个被访问的结点
0 0
- LeetCode Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- LeetCode:Binary Tree Postorder Traversal
- Leetcode Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- [LeetCode] Binary Tree Postorder Traversal
- leetcode Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- LeetCode | Binary Tree Postorder Traversal
- Leetcode: Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal - LeetCode
- LeetCode - Binary Tree Postorder Traversal
- [LeetCode]Binary Tree Postorder Traversal
- Binary Tree Postorder Traversal -- LeetCode
- [LeetCode]Binary Tree Postorder Traversal
- 【LeetCode】Binary Tree Postorder Traversal
- 我的java学习路之循环学习应用demo1九九乘法表
- matlab中创建一维数组变量的方法
- struts2+jquery+ajax实现传输List数据并解析
- java中讲讲FileInputStream的用法,举例?
- JavaScript中常用的DOM操作函数
- 【leetcode】binary-tree-postorder-traversal
- mutableCopy与copy在面试中的那些坑你知道吗?
- Bootstrap初学
- [Leetcode]_21 Merge Two Sorted Lists
- ubuntu 下配置dlib-18.16 在QT中使用
- Ubuntu下用C语言访问MySQL数据库
- 【smoj 1167】松果
- java中讲讲InputStream的用法,举例?
- 程序员的底色(IDE color scheme、CLI 命令行界面)