Determine if the binary tree has a root-to-leaf path

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

  1. Traverse the binary tree, using depth first search (PreOrder traversal).
  2. During DFS traversal, at every node, deduct node value from input number.
  3. Pass the resultant value to its children (left and right subtree).
  4. 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.






?? 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

8 年

Marco Zanella Yes it do applies ..!

回复
Marco Zanella

Ph.D. Computer Science

8 年

This clearly applies to tree of arbitrary arity, doesn't it?

回复

要查看或添加评论,请登录

?? Saral Saxena ???????的更多文章

社区洞察

其他会员也浏览了