leetcode:Binary Tree Preorder Traversal 先序遍历
来源:互联网 发布:菲律宾网络博客靠谱吗 编辑:程序博客网 时间:2024/05/22 23:00
/** * Given a binary tree, return the preorder traversal of its nodes' values. * Note: Recursive solution is trivial, could you do it iteratively?*//// Test Unit/* * 1 * / \ * 2 3 * / * 4 * \ * 5 */#include <iostream>#include <stack>#include <vector>using namespace std;struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {}};class Solution{public: Solution(){}; ~Solution(){}; vector<int> preorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> s; if(!root) return res; s.push(root); while(!s.empty()){ TreeNode* p=s.top(); res.push_back(p->val); s.pop(); if(p->right) s.push(p->right); if(p->left) s.push(p->left); } return res; }};int main(int argc, char** argv) { TreeNode root(1); TreeNode node2(2); TreeNode node3(3); TreeNode node4(4); TreeNode node5(5); root.left = &node2; root.right = &node3; node3.left = &node4; node4.right = &node5; Solution s; for (auto i : s.preorderTraversal(&root)) cout << i << " "; cout << endl; return 0;}
阅读全文
0 0
- [leetcode] Binary Tree Preorder Traversal 非递归先序遍历
- 【leetcode 先序遍历】Binary Tree Preorder Traversal
- [C++]LeetCode: 95 Binary Tree Preorder Traversal (先序遍历)
- leetcode:Binary Tree Preorder Traversal 先序遍历
- Binary Tree Preorder Traversal -先序遍历
- 二叉树的先序遍历 Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal--二叉树的先序遍历
- binary-tree-preorder-traversal(先序遍历二叉树)
- 【leetcode】非递归先序遍历二叉树(Binary Tree Preorder Traversal)
- [LeetCode] Binary Tree Preorder Traversal (非递归的先序遍历)
- LeetCode 144 Binary Tree Preorder Traversal (先序遍历二叉树)
- Binary Tree Preorder Traversal 二叉树的先序@LeetCode
- leetcode---binary-tree-preorder-traversal---树前序遍历
- Binary Tree Preorder Traversal 二叉树的先序遍历,使用堆栈,非递归
- 144. Binary Tree Preorder Traversal (二叉树的先序遍历)
- 144. Binary Tree Preorder Traversal 【先序遍历 + 栈模拟递归】
- LeetCode Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- JMeter 参数化之利用JDBC Connection Configuration从数据库读取数据并关联变量
- 【JSP学习笔记(4)】——数据库应用
- hdu 1009 FatMouse' Trade
- STL序列式容器概述
- 怎么比较两个json字符串完全相等
- leetcode:Binary Tree Preorder Traversal 先序遍历
- excle.分列.仅仅随笔
- c++内存泄露排查思路
- JavaScript中的DOM
- Hibernate 介绍
- 2017Google Codejam round2 Problem B. Roller Coaster Scheduling
- CodeForces 805AFake NP
- Selenium自动化测试框架和个人见解
- Python可迭代对象,迭代器,生成器的区别