Path With Given Sequence (medium)
Problem Statement
Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.
Try it yourself
Try solving this question here:
import java.util.*;class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}};class PathWithGivenSequence {public static boolean findPath(TreeNode root, int[] sequence) {// TODO: Write your code herereturn false;}public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(0);root.right = new TreeNode(1);root.left.left = new TreeNode(1);root.right.left = new TreeNode(6);root.right.right = new TreeNode(5);System.out.println("Tree has path sequence: " + PathWithGivenSequence.findPath(root, new int[] { 1, 0, 7 }));System.out.println("Tree has path sequence: " + PathWithGivenSequence.findPath(root, new int[] { 1, 1, 6 }));}}
Solution
This problem follows the Binary Tree Path Sum pattern. We can follow the same DFS ...