112 Title: Total Path

One. Problem Description

Given a binary tree and a destination and determines whether the root node to the leaf node in the tree path exists, all the nodes on this route, and equal to the target value is added.

Description: leaf node is a node has no child nodes.

Example: 

Given by a binary tree, and the target and sum = 22,

 

               5

              /   \

            4    8

            /      / \

          11  13  4

           /  \         \

         7    2          1

Returns true, because the presence of the target path and the root node to the leaf node 22 5-> 4-> 11-> 2.

two. Problem-solving ideas

Step body: the method of recursive depth-first traversal + judged.

Step a: Construction of a recursive function (root, has accumulated values ​​val, target tacket).

Step two: Analyzing two: If a leaf node and the root val == tacket returns true, if the non-leaf node of the root followed by converting into root.left root node and recursively root.right, as long as one is true, return true.

Step three: Repeat Step two: until all nodes traversed.

three. Results of the

When execution: 0 ms, defeated 100.00% of users in all java submission

Memory consumption: 37.5 MB, defeated 57.49% of all users in java submission

four. Java code

class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
         if(root==null) {
            return false;
        }else {
            return getTree(root,root.val,sum);
        }
    }
    
    public boolean getTree(TreeNode root,int num,int tacket) {
        
        if(root.left==null&&root.right==null&&num==tacket) {
            return true;
        }
        
        if(root.left!=null&&getTree(root.left,num+root.left.val,tacket)) {
            return true;
        }
        
        if(root.right!=null&&getTree(root.right,num+root.right.val,tacket)) {
            return true;
        }
        
        return false;
        
        
    }
    
    
}

 

Guess you like

Origin www.cnblogs.com/xiaobaidashu/p/11864455.html