Print All Paths in a Binary Tree with a Given Sum - Visualization
Problem Statement
Examples
Solution
Algorithm Steps
Code
C
C++
Python
Java
JS
Go
Rust
Kotlin
Swift
TS
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left, *right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}
void printPath(int path[], int len) {
for (int i = 0; i < len; i++) {
printf("%d ", path[i]);
}
printf("\n");
}
void dfs(TreeNode* root, int targetSum, int currentSum, int path[], int level) {
if (!root) return;
path[level] = root->val;
currentSum += root->val;
if (!root->left && !root->right && currentSum == targetSum) {
printPath(path, level + 1);
}
dfs(root->left, targetSum, currentSum, path, level + 1);
dfs(root->right, targetSum, currentSum, path, level + 1);
}
void printPaths(TreeNode* root, int targetSum) {
int path[100];
dfs(root, targetSum, 0, path, 0);
}
int main() {
TreeNode* root = createNode(5);
root->left = createNode(4);
root->right = createNode(8);
root->left->left = createNode(11);
root->left->left->left = createNode(7);
root->left->left->right = createNode(2);
root->right->left = createNode(13);
root->right->right = createNode(4);
root->right->right->right = createNode(1);
printPaths(root, 22);
return 0;
}
Comments
Loading comments...