LeetCode 144:Binary Tree Preorder Traversal
来源:互联网 发布:和日本人谈恋爱 知乎 编辑:程序博客网 时间:2024/06/05 17:27
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
Note: Recursive solution is trivial, could you do it iteratively?
//递归方法:利用一个中间函数,将res作为输入参数 class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; return tmpFunction(root, res); } vector<int> tmpFunction(TreeNode* root, vector<int> &res){ if (root == NULL) return res; res.push_back(root->val); tmpFunction(root->left, res); tmpFunction(root->right, res); return res; } };
//非递归方法: //利用一个栈结构,现将头结点root压入栈中,然后从stack中弹出栈顶节点,记为tmp,然后将tmp的值压入vector<int> res中, //再将节点tmp的右孩子(不为空的话)先压入stack中,最后将tmp的左孩子(不为空的话)压入stack中, //不断重复以上操作,直到stack为空 class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> s; TreeNode* tmp; if (root == NULL) return res; else { s.push(root); while (!s.empty()) { tmp = s.top(); s.pop(); res.push_back(tmp->val); if (tmp->right != NULL) s.push(tmp->right); if (tmp->left != NULL) s.push(tmp->left); } } return res; } };
0 0
- LeetCode(144)Binary Tree Preorder Traversal
- LeetCode: Binary Tree Preorder Traversal [144]
- [leetcode 144]Binary Tree Preorder Traversal
- leetcode || 144、Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal - LeetCode 144
- LeetCode 144 : Binary Tree Preorder Traversal
- LeetCode 144 Binary Tree Preorder Traversal
- LeetCode 144: Binary Tree Preorder Traversal
- Leetcode[144]-Binary Tree Preorder Traversal
- leetcode(144):Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal (leetcode 144)
- leetcode[144]:Binary Tree Preorder Traversal
- [Leetcode 144, Medium] Binary Tree Preorder Traversal
- LeetCode(144) Binary Tree Preorder Traversal
- 【LeetCode】(144)Binary Tree Preorder Traversal(Easy)
- Leetcode #144 Binary Tree Preorder Traversal
- leetcode: (144) Binary Tree Preorder Traversal
- leetCode #144 Binary Tree Preorder Traversal
- 关于更新局部listview中数据的问题
- 阅读任玉刚博客有感
- webdriver UI自动化测试执行JS脚本
- vc中关闭对话框dialog
- KING_UNITY学习之鼠标点击地面控制人物移动
- LeetCode 144:Binary Tree Preorder Traversal
- qpixmap 鼠标移动,局部放大
- 使用python重写上篇文章的内容分析工具
- range,hash,list分区
- php【基础学习七】string操作
- Android中string资源文件使用技巧
- css 文字长时不换行 显示...
- 周记——20151221
- List is a raw type. References to generic type List<E> should be parameterized