Thursday, September 10, 2020

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.

Approach: Use preorder traversal.

        public bool HasPathSum(int sum)
        {
            if (this.Root == null && sum != 0)
            {
                return false;
            }
            return this.HasPathSum(this.Root, sum);
        }

        private bool HasPathSum(BinaryTreeNode node, int sum)
        {
            if (node != null)
            {
                int targetSum = sum - node.Value;

                if (node.LeftNode == null && node.RightNode == null)
                {
                    return targetSum == 0;
                }

                return this.HasPathSum(node.LeftNode, targetSum) || this.HasPathSum(node.RightNode, targetSum);
            }
            return false;
        }

No comments:

Post a Comment