Path sum LeetCode--

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/kingslave1/article/details/84366563

Description of the problem: 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 the following binary tree, and the target, and  sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1

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

 

Thinking: binary tree traversal practice inseparable from its operation, to judge whether the root node to a leaf node in the tree path exists, this path is equal to the sum value of all the nodes and the target sum, determines only the left subtree of the tree value is the sum of the path node or right subtree root node to a leaf node is the presence of a value to the root node sum-. Recursive to turn a leaf node with this thinking.

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public bool HasPathSum(TreeNode root, int sum) {
            if (root == null)
            {
                return false;
            }
            if (root.left == null && root.right == null)
            {
                if (root.val == sum)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            bool leftFlag = false, rightFlag = false;
            if (root.left != null)
            {
                leftFlag = HasPathSum(root.left, sum - root.val);
            }
            if (root.right != null)
            {
                rightFlag = HasPathSum(root.right, sum - root.val);
            }
            return leftFlag || rightFlag;
        }
}

 

 

Guess you like

Origin blog.csdn.net/kingslave1/article/details/84366563