leetcode 虐我篇之(十四)Binary Tree Preorder Traversal
来源:互联网 发布:北美洲国家 知乎 编辑:程序博客网 时间:2024/04/29 14:02
距离上次做题,好像过去了有快两个星期了吧,因为最近在看书和做项目,就没有去做题,到现在看完两本书了,想再回来编编程序,熟悉熟悉。而且最近有比较多的二叉树的例子,刚好这上面题目就是关于这方面的,所以就找到了这一题Binary Tree Preorder Traversal来做。题目描述如下:
Given a binary tree, return the preorder traversal of its nodes' values.For example:Given binary tree {1,#,2,3}, 1 \ 2 / 3return [1,2,3].Note: Recursive solution is trivial, could you do it iteratively?这道题相信看过二叉树的数据结构的都能写出其递归形式的代码,这里给出我的形式:
std::vector<int> preorderTraversal_Recursive(TreeNode *root) {std::vector<int> result,temp;if(!root)return result;result.push_back(root->val);temp = preorderTraversal(root->left);result.insert(result.end(),temp.begin(),temp.end());temp.clear();temp = preorderTraversal(root->right);result.insert(result.end(),temp.begin(),temp.end());return result;}当然了,题目有另外一个提示说,能不能用迭代的方法去写。好像很多书上讲二叉树遍历都是用递归的,用迭代的比较少,刚好又可以再次熟悉一下。其实迭代的方法,就是将节点入栈,然后将栈中内容pop出来,再将其右儿子和左儿子先后放到栈里面,再继续出栈。就这样循环,直到栈为空。代码如下:
std::vector<int> preorderTraversal(TreeNode *root) {std::vector<int> result;std::stack<TreeNode *> treeStack;if (!root){return result;}treeStack.push(root);//when the stack is not empty, go loopwhile(!treeStack.empty()){TreeNode *node = treeStack.top();result.push_back(node->val);treeStack.pop();//right child first push into the stackif (node->right){treeStack.push(node->right);}if (node->left){treeStack.push(node->left);}}return result;}代码也是比较简单易懂,关键是要想到用栈这种数据结构去存储,还有入栈的顺序。
0 0
- leetcode 虐我篇之(十四)Binary Tree Preorder Traversal
- LeetCode 之 Binary Tree Preorder Traversal
- LeetCode之Binary Tree Preorder Traversal
- leetcode之Binary Tree Preorder Traversal
- LeetCode 之 preorder traversal of binary tree
- LeetCode之Binary Tree Preorder Traversal
- leetcode之Binary Tree Preorder Traversal
- LeetCode 之 Binary Tree Preorder Traversal
- LeetCode 之 Binary Tree Preorder Traversal(树)
- (leetcode)Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal (leetcode 144)
- LeetCode Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- Leetcode Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- ios中的设计模式之class Clusters
- Bootstrap3.0学习第十五轮(大屏幕介绍、页面标题、缩略图、警示框、Well)
- CString读文件显示乱码的万能处理方法
- linux 目录和用户权限命令
- 工作分配
- leetcode 虐我篇之(十四)Binary Tree Preorder Traversal
- 写软件不是造汽车
- iOS图片拉伸技巧
- 黑马程序员—因为感恩,所以我也来深圳黑马当班主任
- Spring3零配置注解实现Bean定义
- Bootstrap3.0学习第十六轮(进度条、媒体对象、列表组、面板)
- Linux文件操作,Linux系统函数和C标准库
- 爱情苏打饼
- zoj 3806 Incircle and Circumcircle