Code-Life
Code-Life copied to clipboard
树上每条路径的获取
leetcode 1457 和 113 都是类似的套路
// 题目要求不能遍历到空节点,可以用此模板,treePath为一条根到叶子节点的路径
void dfs(TreeNode* rt, vector<int> treePath) {
treePath.push_back(rt);
if (!rt->left && !rt->right) {
// 看treePath是否题目满足情况, 这里不返回,因为还要pop_back
check(treePath);
}
if (rt->left)
dfs(rt->left, treePath);
if (rt->right)
dfs(rt->right, treePath);
treePath.pop_back();
}