BM29 The path with a certain value in the binary tree (1)

describe

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

1. The path of this question is defined as the node from the root node of the tree down to the leaf node

2. A leaf node refers to a node without child nodes

3. The path can only go from parent node to child node, not from child node to parent node

4. The total number of nodes is n


For example:
given the following binary tree, sum=22,


Returns true because there is a path 25→4→11→2 whose sum of node values ​​is 22

data range:

1. The number of nodes on the tree satisfies 0≤n≤10000

2. The value of each node satisfies ∣val∣≤1000

Requirements: space complexity O(n)O(n), time complexity O(n)O(n)

Advanced: space complexity O(tree height)O(tree height), time complexity O(n)O(n)

Example 1

enter:

{5,4,8,1,11,#,9,#,#,2,7},22

return value:

true

Example 2

enter:

{1,2},0

return value:

false

Example 3

enter:

{1,2},3

return value:
true

Example 4

enter:

{},0

return value:

false

 Code (recursive sum of left and right subtrees)

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return bool布尔型
     */
    boolean flag=false;
    void dfs(TreeNode root ,int s,int sum){
        if(root==null){  //到达叶子节点,就返回递归
            return;
        }
        s=s+root.val;
        if(root.left==null&&root.right==null&&s==sum){  //到达叶子节点
            flag=true;  //如果和等于sum
        }
        else{//如果没有到达叶子节点,左右子树递归
            if(root.left!=null) dfs(root.left,s,sum);
            if(root.right!=null) dfs(root.right,s,sum);
        }
    }
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
       dfs(root,0,sum);
        return flag;
    }
}

Guess you like

Origin blog.csdn.net/hgnuxc_1993/article/details/123657080