[LeetCode]Binary Tree Preorder Traversal
2015-11-22 16:41
267 查看
题目描述:(链接)
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?
解题思路:
迭代版:
递归版:
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?
解题思路:
迭代版:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> result; stack<TreeNode *> cache; TreeNode *p = root; if (p != nullptr) { cache.push(p); } while (!cache.empty()) { p = cache.top(); cache.pop(); result.push_back(p->val); if (p->right != nullptr) { cache.push(p->right); } if (p->left != nullptr) { cache.push(p->left); } } return result; } };
递归版:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if (root != nullptr) { result.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); } return result; } private: vector<int> result; };
相关文章推荐
- 函数buf_pool_init
- 第12周—项目3(2)图的广度遍历
- Android .gitignore文件示例
- LeetCode 062 Unique Paths
- 【C语言】【笔试题】模拟实现strncat
- getCacheDir()、getFilesDir()、getExternalFilesDir()、getExternalCacheDir()的作用,getfilesdir
- PowerShell GUI之创建Button和输入框
- standalone在XML里的作用
- LeetCode 子 Climbing Stairs
- linux 时间同步
- 第2章 如何构建布局良好的Windows程序
- Android如何构建一个https请求的httpClient
- POJ3580 SuperMemo(Splay的区间操作)
- ios9网络请求https适配
- secureCRT sftp 使用
- 问题2 String类equals 和 “==” 比较
- 信息安全系统设计基础第十一周学习总结
- POJ3580 SuperMemo(Splay的区间操作)
- 哈夫曼树及解码
- php中一些函数的用法