第十四周算法分析与设计:Binary Tree Preorder Traversal
来源:互联网 发布:淘宝网儿童保护电插头 编辑:程序博客网 时间:2024/06/02 10:09
问题描述:
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?
问题出自此处
解法思路:
1.递归:看见遍历不由自主想到了递归,先序遍历就是先遍历根节点,再遍历左右节点。一开始不懂#
是啥意思,以为val
用这个字符代表没有子树,然后转念一想不对啊,val
的数据类型是int
,不可能存得了这个,所以这个应该就是空指针的意思!
class Solution {private: vector<int> result;public: vector<int> preorderTraversal(TreeNode* root) { if(root == NULL) return result; result.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); return result; }};
嘛,这个就是
2.循环。惊了!准备写博客的时候才发现题目要求用迭代?!害我终于以为自己可以用个迭代解决中等难度题时白白暗爽了一波!好吧,进入正题,在迭代中遍历,可以使用栈来帮助解决——不过要注意的是:先取数,再弹出该节点(以免重复算);然后先进栈右节点,再进栈左节点。(保证下次循环栈顶取出的是左节点)
class Solution {private: vector<int> result;public: vector<int> preorderTraversal(TreeNode* root) { if(root == NULL) return result; stack<TreeNode*> st; st.push(root); while(!st.empty()) { TreeNode* cur = st.top(); result.push_back(cur->val); st.pop(); if(cur->right) st.push(cur->right); if(cur->left) st.push(cur->left); } return result; }};
这个时间复杂度也是
+1s~
阅读全文
0 0
- 第十四周算法分析与设计:Binary Tree Preorder Traversal
- 算法分析与设计丨第四周丨LeetCode(8)——Binary Tree Level Order Traversal(Medium)
- LeetCode算法题目:Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- IntelliJ IDEA 快捷键大全
- Spring:IOC—控制反转(1)
- 【vagrant up】 default: Warning: Authentication failure. Retrying
- IBATIS列名无效
- IOS Swift3 基本图形绘制
- 第十四周算法分析与设计:Binary Tree Preorder Traversal
- 打印楼梯,同时在楼梯上方打印两个笑脸
- C++随记(三)---动态分配内存问题(2)
- 基于STM32wifi小车制作(五)-基本完工
- 5月26日,每日20行。
- 循环神经网络(RNN, Recurrent Neural Networks)介绍
- zoj1203
- 1.1 Getting the Source Tree
- Java中的static详解