LeetCode 之 Binary Tree Preorder Traversal
2016-01-22 14:45
323 查看
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
使用栈实现遍历,代码如下:
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?
使用栈实现遍历,代码如下:
vector<int> preorderTraversal(TreeNode* root) { stack<TreeNode*> tree; vector<int> ans; if(!root) return ans; tree.push(root); while(tree.size()){ TreeNode* temp=tree.top(); ans.push_back(temp->val); tree.pop(); if(temp->right) tree.push(temp->right); if(temp->left) tree.push(temp->left); } return ans; }
相关文章推荐
- Objective-C:模拟按钮点击事件理解代理模式
- VC 操作word部分代码(利用剪切板取得Word中的图片,ClipBoard, Addpicture)
- MySQL C API mysql_free_result() 详解
- react-native布局篇
- jQuery插件:跨浏览器复制jQuery-zclip
- ELK日志分析集群部署笔记
- 你没钱没男人,却有粗糙的脸和巨大的胃
- Maven项目下update maven后Eclipse报错:java.lang.ClassNotFoundException: ContextLoaderListener
- Windows下Redis的安装使用
- 中国剩余定理和欧几里得定理
- Android ViewPager PagerAdapter
- SYN Cookie的原理和实现
- JS中实现字符串和数组的相互转化
- 2016年初总结
- 非UI主线程如何弹出Toast以及Handler.post()流程分析
- 去掉Cell选中效果
- 报道帖-简单的自我介绍
- vim tee cat
- HashMap实现原理分析
- 热门搜索不规则Textview FlowLayout