题目地址:
https://leetcode.com/problems/binary-tree-preorder-traversal/
先序遍历二叉树,并存入一个list里。
法1:DFS,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
* right(right) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
dfs(root, res);
return res;
}
void dfs(TreeNode* root, vector<int>& res) {
if (!root) return;
res.push_back(root->val);
dfs(root->left, res);
dfs(root->right, res);
}
};
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h), h h h为二叉树深度,也就是递归栈深度。
法2:用栈模拟递归。从树根开始,每次遍历左链,同时将非空右孩子入栈。左链遍历完毕之后从栈里弹一个元素,接着重复上述操作。代码如下:
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> stk;
auto cur = root;
while (cur || stk.size()) {
while (cur) {
res.push_back(cur->val);
if (cur->right) stk.push(cur->right);
cur = cur->left;
}
if (stk.size()) {
cur = stk.top();
stk.pop();
}
}
return res;
}
};
时空复杂度和之前一样。