zoukankan      html  css  js  c++  java
  • 二叉树的路径总和

    原创:转载需注明原创地址 https://www.cnblogs.com/fanerwei222/p/12145869.html

    查询二叉树的路径之和是否等于一个给定的值!

        class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
            TreeNode(int x) { val = x; }
        }
    
        public boolean hasPathSum(TreeNode root, int sum) {
            if (root == null) {
                return false;
            }
    
            return hasPathS(root.left, root.right, root.val, sum);
        }
    
        public static boolean hasPathS(TreeNode left, TreeNode right,int pre, int sum){
            if (left == null && right == null) {
                return pre == sum;
            }
            if (left != null && right != null) {
                return hasPathS(left.left, left.right, pre + left.val, sum) || hasPathS(right.left, right.right, pre + right.val, sum);
            }
            if (left != null) {
                return hasPathS(left.left, left.right, pre + left.val, sum);
            }
            if (right != null) {
                return hasPathS(right.left, right.right, pre + right.val, sum);
            }
    
            return pre == sum;
        }
  • 相关阅读:
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    星空雅梦
    C语言基础知识【作用域规则】
  • 原文地址:https://www.cnblogs.com/fanerwei222/p/12145869.html
Copyright © 2011-2022 走看看