(写给未来遗忘的自己)
前序遍历:
题目:
代码:
/*** 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>input;preorderTraversal_help(root,input);return input;}void preorderTraversal_help(TreeNode* root,vector<int>&input){if(root==nullptr) return ;input.push_back(root->val);preorderTraversal_help(root->left,input);preorderTraversal_help(root->right,input);}
};
后序遍历:
题目:
代码:
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int>input;postorderTraversal_help(root,input);return input;}void postorderTraversal_help(TreeNode* root,vector<int>&input){if(root==nullptr) return;postorderTraversal_help(root->left,input);postorderTraversal_help(root->right,input);input.push_back(root->val);}
};
中序遍历:
题目:
代码:
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {vector<int>input;inorderTraversal_help(root,input);return input;}void inorderTraversal_help(TreeNode* root,vector<int>&input){if(root==nullptr) return;inorderTraversal_help(root->left,input);input.push_back(root->val);inorderTraversal_help(root->right,input);}
};
思路与总结:
前面写过这个代码。
下面就是递归遍历的一个代码实现的主逻辑。
void preorderTraversal_help(TreeNode* root,vector<int>&input){if(root==nullptr) return ;input.push_back(root->val);preorderTraversal_help(root->left,input);preorderTraversal_help(root->right,input);}
中:
input.push_back(root->val);
左:
preorderTraversal_help(root->left,input);
右:
preorderTraversal_help(root->right,input);
上面三行代码,中左右根据遍历的顺序写好就可以,开头检查一下是否为空。
数组的传入需要以引用的方式,直接可以修改,否则就会一直拷贝,然后主函数的地方的return有问题。
void preorderTraversal_help(TreeNode* root,vector<int>&input)