【binary-tree-preorder-traversal】
来源:互联网 发布:战舰世界雷鸣数据 编辑:程序博客网 时间:2024/06/05 16:19
Given a binary tree, return the preordertraversal 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?
方法一:
非递归实现:
class Solution{public:vector<int> preorderTraversal(TreeNode* root){vector<int> res;if (!root){return res;}stack<TreeNode*> st;st.push(root);while (st.size()){TreeNode* tmp = st.top();st.pop();res.push_back(tmp->val);if (tmp->right){st.push(tmp->right);}if (tmp->left){st.push(tmp->left);}}return res;}};
递归实现
class Solution{public:vector<int> preorderTraversal(TreeNode* root){vector<int> ans;LRD(ans, root);return ans;}void LRD(vector<int>&ans, TreeNode* root){if (root==NULL){return;} ans.push_back(root->val);LRD(ans, root->left);LRD(ans, root->right);}};
阅读全文
0 0
- 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
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Codeforces Round #431 (Div. 2) Tell Your World
- Bigtable: A Distributed Storage System for Structured Data : part5 Implementation
- 代码规范和Android项目中的一些可用工具
- ASCII、Unicode和UTF-8
- 基于NGINX的安全加固
- 【binary-tree-preorder-traversal】
- 301,404,网站地图
- 【备忘】Java菜鸟到大牛学习路线之高级篇
- 数学建模程序员从入门到进阶系列博客——目录
- 锁:可重入锁,可中断锁,公平锁,读写锁
- (3) linux下zookeeper伪集群搭建
- UnsupportedOperationException:setProperty must be overridden by all subclasses of SOAPMessage解决方法>有效
- 云计算之路-阿里云上-新车限行:新购服务器无法访问任何远程25端口
- Sensors