递归三部曲:
确定函数返回值和参数 直接每一步插入对应元素,不需要返回值
终止条件if (root==null)return;
单层逻辑 前序遍历,先插入中间结点,再调用左右结点。
code:
/**
* 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 {
private:
vector<int>result;
void fronttraversal(TreeNode* root)
{
if(root==NULL)return;
result.push_back(root->val);
fronttraversal(root->left);
fronttraversal(root->right);
return;
}
public:
vector<int> preorderTraversal(TreeNode* root) {
result.clear();
fronttraversal(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;
stack<TreeNode*>st;
if(root==NULL)return result;
st.push(root);
while(!st.empty())
{
TreeNode* cur=st.top();
st.pop();
result.push_back(cur->val);
if(cur->right)st.push(cur->right);
if(cur->left)st.push(cur->left);
}
return result;
}
};