113. Path Sum II
发布时间:2020-12-14 04:28:13 所属栏目:大数据 来源:网络整理
导读:Given a binary tree and a sum,find all root-to-leaf paths where each path‘s sum equals the given sum. Note:?A leaf is a node with no children. Example: Given the below binary tree and? sum = 22 , 5 / 4 8 / / 11 13 4 / / 7 2 5 1 Return:
Given a binary tree and a sum,find all root-to-leaf paths where each path‘s sum equals the given sum. Note:?A leaf is a node with no children. Example: Given the below binary tree and? 5 / 4 8 / / 11 13 4 / / 7 2 5 1 Return: [ [5,4,11,2],[5,8,5] ] ? Approach #1: C++. [Recursive] /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x),left(NULL),right(NULL) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root,int sum) { if (root == NULL) return ans; vector<int> temp; helper(root,temp,sum); return ans; } private: vector<vector<int>> ans; void helper(TreeNode* root,vector<int> temp,int cur,int sum) { if (root == NULL) return; temp.push_back(root->val); if (root->left == NULL && root->right == NULL && cur+root->val == sum) { ans.push_back(temp); return; } helper(root->left,cur+root->val,sum); helper(root->right,sum); } };
Approach #2: Java.[DFS+Stack] /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<List<Integer>> pathSum(TreeNode root,int sum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> path = new ArrayList<>(); Stack<TreeNode> stack = new Stack<>(); int curSum = 0; TreeNode cur = root; TreeNode prev = null; while (cur != null || !stack.isEmpty()) { while (cur != null) { stack.push(cur); curSum += cur.val; path.add(cur.val); cur = cur.left; } cur = stack.peek(); if (cur.right != null & cur.right != prev) { cur = cur.right; continue; } if (cur.left == null && cur.right == null && curSum == sum) res.add(new ArrayList<Integer>(path)); prev = cur; stack.pop(); path.remove(path.size()-1); curSum -= cur.val; cur = null; } return res; } }
Approach #3: Python. [BFS+Queue] # Definition for a binary tree node. # class TreeNode(object): # def __init__(self,x): # self.val = x # self.left = None # self.right = None class Solution(object): def pathSum(self,root,sum): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ if root == None: return [] res = [] queue = [(root,root.val,[root.val])] while queue: curr,val,ls = queue.pop() if not curr.left and not curr.right and val == sum: res.append(ls) if curr.left: queue.append((curr.left,val+curr.left.val,ls+[curr.left.val])) if curr.right: queue.append((curr.right,val+curr.right.val,ls+[curr.right.val])) return res (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |