Binary Tree Path Sum (easy)
Problem Statement
Given a binary tree and a number ‘S’, find if the tree has a path from root-to-leaf such that the sum of all the node values of that path equals ‘S’.
Try it yourself
Try solving this question here:
class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}};class TreePathSum {public static boolean hasPath(TreeNode root, int sum) {// TODO: Write your code herereturn false;}public static void main(String[] args) {TreeNode root = new TreeNode(12);root.left = new TreeNode(7);root.right = new TreeNode(1);root.left.left = new TreeNode(9);root.right.left = new TreeNode(10);root.right.right = new TreeNode(5);System.out.println("Tree has path: " + TreePathSum.hasPath(root, 23));System.out.println("Tree has path: " + TreePathSum.hasPath(root, 16));}}
Solution
As we are trying to search for a root-to-leaf path, we can use the Depth First Search (DFS) technique to solve this problem.
To recursively traverse a binary tree in a DFS fashion, we can start from the root and at every step, make two recursive calls one for the left and one for the right child.
Here ...