LeetCode 112. Path Sum(路径和)
来源:互联网 发布:大数据徐子沛 编辑:程序博客网 时间:2024/05/21 09:44
原题网址:https://leetcode.com/problems/path-sum/
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2
which sum is 22.
方法:递归,自底向上。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) return false; if (root.left == null && root.right == null) return root.val == sum; if (root.left != null && hasPathSum(root.left, sum - root.val)) return true; if (root.right != null && hasPathSum(root.right, sum - root.val)) return true; return false; }}
0 0
- LeetCode 112. Path Sum(路径和)
- LeetCode | Path Sum(路径和)
- LeetCode Path Sum 路径和
- [LeetCode] 路径和 Path Sum
- leetcode Path Sum 路径和
- leetcode 112.Path Sum-树路径和|深度遍历
- Leetcode 112. Path Sum 路径和 解题报告
- LeetCode | Path Sum II(路径和2)
- LeetCode | Minimum Path Sum(最小路径和)
- LeetCode OJ 之 Path Sum(求路径和)
- LeetCode OJ 之 Path Sum II (路径和 - 二)
- LeetCode OJ 之 Minimum Path Sum (最小路径和)
- LeetCode 64. Minimum Path Sum(最小路径和)
- LeetCode 113. Path Sum II(路径和)
- LeetCode--Minimum Path Sum (最小路径和)Python
- Path Sum 二叉树路径和 @LeetCode
- LeetCode Path Sum II路径和II
- [leetcode]Minimum Path Sum 最小路径和
- LeetCode 109. Convert Sorted List to Binary Search Tree(链表到二叉搜索树)
- leetcode #24 in cpp
- Leetcode 133. Clone Graph & 138. Copy List with Random Pointer
- LeetCode 110. Balanced Binary Tree(平衡二叉树)
- LeetCode 111. Minimum Depth of Binary Tree(二叉树最小深度)
- LeetCode 112. Path Sum(路径和)
- 软件架构设计原则和模式(上):分层架构设计
- 最新的版的PostgresSQL引入了BRIN索引
- LeetCode 113. Path Sum II(路径和)
- LeetCode 114. Flatten Binary Tree to Linked List(摊平二叉树)
- WindowBuilder的离线安装与使用
- git使用命令
- apache结合svn笔记
- tp执行流程分析