目录
文章讲解:代码随想录(programmercarl.com)
视频讲解:每次写递归都要靠直觉? 这次带你学透二叉树的递归遍历!
-
理论基础
-
二叉树的递归遍历
前序遍历:
class Solution { public: void traversal(TreeNode* cur, vector<int>& vec) { if (cur == NULL) return; vec.push_back(cur->val); traversal(cur->left, vec); traversal(cur->right, vec); } vector<int> preorderTraversal(TreeNode* root) { vector<int> result; traversal(root, result); return result; } };
中序遍历:
void traversal(TreeNode* cur, vector<int>& vec) { if (cur == NULL) return; traversal(cur->left, vec); vec.push_back(cur->val); traversal(cur->right, vec); }
后序遍历:
void traversal(TreeNode* cur, vector<int>& vec) { if (cur == NULL) return; traversal(cur->left, vec); traversal(cur->right, vec); vec.push_back(cur->val); }