Determine if the binary tree has a root-to-leaf path
?? Saral Saxena ??????
?11K+ Followers | Linkedin Top Voice || Associate Director || 15+ Years in Java, Microservices, Kafka, Spring Boot, Cloud Technologies (AWS, GCP) | Agile , K8s ,DevOps & CI/CD Expert
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
so the Algo for this goes like
- Traverse the binary tree, using depth first search (PreOrder traversal).
- During DFS traversal, at every node, deduct node value from input number.
- Pass the resultant value to its children (left and right subtree).
- When we encounter the leaf node, the resultant value will reduced to zero (if path exist).
Let us look into the binary tree, shown in below figure . We are subtracting the respective node value at each level. We can see that leaf node F is having value equals 0. So, A->C->F is root to leaf path, having sum equals 110.
?11K+ Followers | Linkedin Top Voice || Associate Director || 15+ Years in Java, Microservices, Kafka, Spring Boot, Cloud Technologies (AWS, GCP) | Agile , K8s ,DevOps & CI/CD Expert
8 年Marco Zanella Yes it do applies ..!
Ph.D. Computer Science
8 年This clearly applies to tree of arbitrary arity, doesn't it?