问题描述:
Share
Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input:[1,null,2,3]
1 \ 2 / 3 Output:[1,2,3]
源码:
递归的写法,很简单的,时间空间100%。
/**
* 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> result;
void preorder(TreeNode* root){
result.push_back(root->val);
if(root->left) preorder(root->left);
if(root->right) preorder(root->right);
}
vector<int> preorderTraversal(TreeNode* root) {
if(!root) return result;
preorder(root);
return result;
}
};
先序的非递归也不难,直接一个栈解决。
/**
* 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> result;
if(!root) return result;
stack<TreeNode*> st;
st.push(root);
while(!st.empty()){
TreeNode *tmp = st.top();
result.push_back(tmp->val);
st.pop();
if(tmp->right) st.push(tmp->right);
if(tmp->left) st.push(tmp->left);
}
return result;
}
};
上一种写法在后序和中序上就比较难弄,下面这种可能会好一点,时间空间都是100%。
/**
* 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> result;
if(!root) return result;
stack<TreeNode*> st;
TreeNode* p = root;
while(!st.empty() || p){
while(p){
result.push_back(p->val);
st.push(p);
p = p->left;
}
if(!st.empty()){
p = st.top();
st.pop();
p = p->right;
}
}
return result;
}
};