本文主要記錄一下leetcode樹之路徑總和node
給定一個二叉樹和一個目標和,判斷該樹中是否存在根節點到葉子節點的路徑,這條路徑上全部節點值相加等於目標和。 說明: 葉子節點是指沒有子節點的節點。 示例: 給定以下二叉樹,以及目標和 sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 返回 true, 由於存在目標和爲 22 的根節點到葉子節點的路徑 5->4->11->2。 來源:力扣(LeetCode) 連接:https://leetcode-cn.com/problems/path-sum 著做權歸領釦網絡全部。商業轉載請聯繫官方受權,非商業轉載請註明出處。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean hasPathSum(TreeNode root, int sum) { if (root == null) { return false; } if (root.left == null && root.right == null) { return sum - root.val == 0; } return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val); } }
這裏採用遞歸的方式來求解,遞歸的終止條件就是root爲null或者左右節點爲null,此時判斷是否有符合條件的sum;以後針對root.left或者root.right遞歸調用hasPathSum,此時sum傳參爲sum - root.val網絡