利用后续遍历

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布尔型
     */
    public boolean preOrder(TreeNode root,int sum,int target){
        if(root.left == null && root.right == null){ //判断是否为叶子节点
            if(sum+root.val == target){
                return true;
            }else{
                return false;
            }
        }
            int tempSum = sum+root.val;
            boolean left = false;
            boolean right = false;
            if(root.left != null){
                left = preOrder(root.left, tempSum,target);
            }
            if(root.right != null){
                right = preOrder(root.right, tempSum,target);
            }
            return left||right;
        
    }
    public boolean hasPathSum (TreeNode root, int sum) {
        // write code here
        if(root == null){
            return false;
        }else{
            return preOrder(root,0,sum);
        }
        
        
    }
}