[LeetCode 题解]: Binary Tree Preorder Traversal
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode 题解]: Binary Tree Preorder Traversal
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前言
?
【LeetCode 題解】系列傳送門:? http://www.cnblogs.com/double-win/category/573499.html
?
1.題目描述
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
2. 題意
?
先序遍歷二叉樹,遞歸的思路是普通的,能否用迭代呢?
?
3. 思路
非遞歸思路:<借助stack>
vector<int> preorderTraversal(TreeNode *root) {stack<TreeNode* > st;vector<int> vi;vi.clear();if(!root) return vi;st.push(root);while(!st.empty()){TreeNode *tmp = st.top();vi.push_back(tmp->val); st.pop();if(tmp->right) st.push(tmp->right);if(tmp->left) st.push(tmp->left);}return vi;}遞歸思路:
class Solution { private:vector<int> vi; public:vector<int> preorderTraversal(TreeNode *root) {vi.clear();if(!root) return vi;preorder(root);return vi;}void preorder(TreeNode* root){if(!root) return;vi.push_back(root->val);preorder(root->left);preorder(root->right);} };4.相關題目
(1)二叉樹的中序遍歷:
(2)二叉樹的后序遍歷:
(3) 二叉樹系列文章:
| 作者:Double_Win 出處: http://www.cnblogs.com/double-win/p/3896010.html? 聲明: 由于本人水平有限,文章在表述和代碼方面如有不妥之處,歡迎批評指正~ |
轉載于:https://www.cnblogs.com/double-win/p/3895822.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的[LeetCode 题解]: Binary Tree Preorder Traversal的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS事件冒泡
- 下一篇: iOS - UITableViewCel