Niuke.com brushing questions-whether there is a path to the specified node in the binary tree

Problem Description

Given a binary tree and a value sum, judge whether there is a path from the root node to the leaf node that the sum of the node values ​​is equal to the sum.

Enter description:
Enter a tree

Output description:
output whether there is a path to the specified sum

Example

Example 1

Enter
22Insert picture description here

Output (path included: 5->4->11->2)
true

Solutions

analysis

  1. Judge all paths recursively, as long as it contains return true, the relationship between different paths is ||.

method

  1. Recursively determine whether the path of the specified sum is included

Code

// 思路1
public class Solution {
    
    
    public boolean hasPathSum (TreeNode root, int sum) {
    
    
        // write code here
        if (root == null) {
    
    
            return false;
        }
        if (root.left == null && root.right == null) {
    
    
            return (sum - root.val == 0);
        }
        return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
    }
}

If you want to test, you can go directly to the link of Niuke.com to do the test

Does the binary tree have the path of the specified node?

Guess you like

Origin blog.csdn.net/qq_35398517/article/details/113137441