LintCode 二叉树的遍历 (非递归)
来源:互联网 发布:淘宝靠谱的数码店 编辑:程序博客网 时间:2024/06/05 20:41
前序:
class Solution {public: /** * @param root: The root of binary tree. * @return: Preorder in vector which contains node values. */ vector<int> preorderTraversal(TreeNode *root) { // write your code here stack<TreeNode*> s; vector<int> res; while (root!= nullptr || !s.empty()) { while (root != nullptr) { res.push_back(root->val); s.push(root); root = root->left; } if (!s.empty()) { root = s.top(); s.pop(); root = root->right; } } return res; }};
中序:
class Solution { /** * @param root: The root of binary tree. * @return: Inorder in vector which contains node values. */public: vector<int> inorderTraversal(TreeNode *root) { // write your code here stack<TreeNode *> s; vector<int> res; while (root!=nullptr || !s.empty()) { while (root != nullptr){ s.push(root); root = root->left; } if (!s.empty()) { root = s.top(); res.push_back(root->val); s.pop(); root = root ->right; } } return res; }};
后续:
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution { /** * @param root: The root of binary tree. * @return: Postorder in vector which contains node values. */public: vector<int> postorderTraversal(TreeNode *root) { // write your code here vector<int> res; stack<TreeNode*> s; TreeNode * cur; TreeNode *pre = nullptr; if (root == nullptr) { return res; } s.push(root); while (!s.empty()) { cur = s.top(); if ((cur->left == nullptr && cur->right == nullptr) || (pre != nullptr && (pre==cur->left || pre == cur->right))) { res.push_back(cur->val); s.pop(); pre = cur; } else { if (cur->right != nullptr) { s.push(cur->right); } if (cur->left != nullptr) { s.push(cur->left); } } } return res; } };
0 0
- LintCode 二叉树的遍历 (非递归)
- 二叉树后续非递归遍历-lintcode
- lintcode-二叉树的前序遍历(非递归)-66
- lintcode-二叉树的中序遍历(非递归)-67
- 二叉树的中序遍历(lintcode)(递归和非递归)
- Lintcode 二叉树的前序遍历 (递归和非递归法)
- Lintcode 二叉树的中序遍历(递归+非递归)
- 【LintCode-66】二叉树的前序遍历(Java实现-递归算法/非递归算法)
- 【LintCode-67】二叉树的中序遍历(Java实现-递归算法/非递归算法)
- LintCode Binary Tree Preorder Traversal二叉树的前序遍历(非递归)
- LintCode Binary Tree Inorder Traversal 二叉树的中序遍历(非递归)
- 二叉树专题-lintcode递归与非递归遍历
- 二叉树的遍历(递归+非递归+层次遍历)
- 二叉树的遍历(非递归)
- 二叉树的遍历(非递归)
- 二叉树的遍历(非递归)
- 二叉树专题-lintcode非递归遍历与总结
- Lintcode 二叉树后序遍历 非递归形式
- 欢迎使用CSDN-markdown编辑器
- JAVA字符串的优化
- 解决httpd: Could not reliably determine the server's fully qualified domain name
- Linux目录树
- JS判断浏览器是否为IE
- LintCode 二叉树的遍历 (非递归)
- JS的构造函数
- Android学习笔记--Animation
- Cloudera Manager5问题之NTP问题
- TimesTen 常见问题答疑(科普篇)
- 正则表达式里字符串”不包含”匹配技巧
- ExtJs 入门教程十四[数据代理 :DataProxy]
- visual studio 编译问题unresolved external symbol
- js中Array数组的操作