-
二叉树前序遍历(递归 + 迭代)
vector<int> res; vector<int> preorderTraversal(TreeNode* root){ preorder(root); return res; } void preorder(TreeNode* root){ if(!root) return; res.push_back(root -> val); preorder(root -> left); preorder(root -> right); }
vector<int> preorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> stk; TreeNode* cur = root; while(cur || !stk.empty()){ while(cur){ stk.push(cur); res.push_back(cur -> val); cur = cur -> left; } cur = stk.top(); stk.pop(); cur = cur -> right; } return res; }
-
二叉树中序遍历(递归 + 迭代)
vector<int> res; vector<int> inorderTraversal(TreeNode* root){ inorder(root); return res; } void inorder(TreeNode* root){ if(!root) return; inorder(root -> left) res.push_back(root -> val); inorder(root -> right); }
vector<int> inorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> stk; TreeNode* cur = root; while(cur || !stk.empty()){ while(cur){ stk.push(cur); cur = cur -> left; } cur = stk.top(); stk.pop(); res.push_back(cur -> val); cur = cur -> right; } return res; }
-
二叉树后序遍历(递归 + 迭代)
vector<int> res; vector<int> postorderTraversal(TreeNode* root){ postorder(root); return res; } void postorder(TreeNode* root){ if(!root) return; preorder(root -> left); preorder(root -> right); res.push_back(root -> val); }
vector<int> postorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> stk; TreeNode* cur = root; while(cur || !stk.empty()){ while(cur){ stk.push(cur); res.push_back(cur -> val); cur = cur -> right; } cur = stk.top(); stk.pop(); cur = cur -> left; } reverse(res.begin(), res.end()); return res; }
-
二叉树层序遍历(BFS + DFS)
vector<vector<int>> levelOrder(TreeNode* root) { queue<TreeNode*> q; vector<vector<int>> res; q.push(root); while(!q.empty()) { int n = q.size(); vector<int> level; for(int i = 0; i < n; ++ i) { TreeNode* cur = q.front(); q.pop(); level.push_back(cur -> val); if(cur -> left) q.push(cur -> left); if(cur -> right) q.push(cur -> right); } res.push_back(level); } return res; }
vector<vector<int>> res; vector<vector<int>> levelOrder(TreeNode* root) { levelorder(root, 0); return res; } void levelorder(TreeNode* root, int level){ if(!root) return; if(level == res.size()) res.emplace_back(); res[level].push_back(root -> val); levelorder(root -> left, level + 1); levelorder(root -> right, level + 1); }