【二叉树经典问题】 144. Binary Tree Preorder Traversal
来源:互联网 发布:nba2k16捏樱木花道数据 编辑:程序博客网 时间:2024/05/18 03:50
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> res; preorder(root,res); return res; } void preorder(TreeNode* root, vector<int>& res){ if(!root) return; res.push_back(root->val); preorder(root->left,res); preorder(root->right,res); }};非递归:
class Solution {public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> s; while(root||!s.empty()){ while(root){ res.push_back(root->val); s.push(root); root=root->left; } root=s.top(); s.pop(); root=root->right; } return res; }};
还有一种非递归很直接:
class Solution {public: vector<int> preorderTraversal(TreeNode *root) { stack<TreeNode*> nodeStack; vector<int> result; //base case if(root==NULL) return result; nodeStack.push(root); while(!nodeStack.empty()) { TreeNode* node= nodeStack.top(); result.push_back(node->val); nodeStack.pop(); if(node->right) nodeStack.push(node->right); if(node->left) nodeStack.push(node->left); } return result; }};
阅读全文
0 0
- 【二叉树经典问题】 144. Binary Tree Preorder Traversal
- 【二叉树经典问题】105. Construct Binary Tree from Preorder and Inorder Traversal
- 二叉树遍历144. Binary Tree Preorder Traversal
- LeetCode 二叉树 | 144. Binary Tree Preorder Traversal
- 【二叉树经典问题】102. Binary Tree Level Order Traversal
- 【二叉树经典问题】94. Binary Tree Inorder Traversal
- 【二叉树经典问题】145. Binary Tree Postorder Traversal
- 144.Binary Tree Preorder Traversal
- 144.Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144.Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- 144. Binary Tree Preorder Traversal
- Python 变量类型
- Java多线程之线程安全与异步执行
- 卷积神经网络中十大拍案叫绝的操作
- Anaconda
- HDU
- 【二叉树经典问题】 144. Binary Tree Preorder Traversal
- Spring,hibernate,struts的面试笔试题
- JVM参数设置、分析
- 类的继承和组合
- 'mysqld_safe' 不是内部或外部命令,也不是可运行的程序 或批处理文件。
- 操作 sd卡 error
- 执行sudo go get出现$GOPATH not set的问题
- VC 关于CEdit基本用法
- effective C++条款三十九解析