zoukankan      html  css  js  c++  java
  • 112. Path Sum

    原题链接:https://leetcode.com/problems/path-sum/description/
    二叉树相关问题,直接深度优先搜索走一波:

    /**
     * Created by clearbug on 2018/2/26.
     */
    public class Solution {
    
        static class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
    
            public TreeNode(int val) {
                this.val = val;
            }
        }
    
        public static void main(String[] args) {
            Solution s = new Solution();
    
            // test1
            TreeNode root = new TreeNode(3);
            root.left = new TreeNode(9);
            root.left.left = new TreeNode(33);
            root.right = new TreeNode(20);
            root.right.left = new TreeNode(15);
            root.right.right = new TreeNode(7);
            System.out.println(s.hasPathSum(root, 45));
            System.out.println(s.hasPathSum(root, 38));
            System.out.println(s.hasPathSum(root, 30));
            System.out.println(s.hasPathSum(root, 46));
            System.out.println(s.hasPathSum(root, 20));
        }
    
        public boolean hasPathSum(TreeNode root, int sum) {
            if (root == null) {
                return false;
            }
            return dfs(root, sum, 0);
        }
    
        private boolean dfs(TreeNode node, int sum, int currentSum) {
            currentSum += node.val;
            if (node.left == null && node.right == null) {
                if (currentSum == sum) {
                    return true;
                }
            } else {
                if (node.left != null) {
                    if (dfs(node.left, sum, currentSum)) {
                        return true;
                    }
                }
                if (node.right != null) {
                    if (dfs(node.right, sum, currentSum)) {
                        return true;
                    }
                }
            }
            return false;
        }
    
    }
    
  • 相关阅读:
    linux-log-files/
    SSL SSH
    C++学习的书籍
    Linux IO 分析
    LINUX 常用操作
    Find Large Files in Linux
    Linux 常见操作
    Linux Performance tool
    /linux-command-line-bash-shortcut-keys/
    Sed
  • 原文地址:https://www.cnblogs.com/optor/p/8585521.html
Copyright © 2011-2022 走看看