1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int pathSum(TreeNode* root, int sum) { 13 queue<TreeNode*> q; 14 int dp[1000]; 15 q.push(root); 16 int index=0; 17 int count=0; 18 while(!q.empty()){ 19 TreeNode* temp=q.front(); 20 q.pop(); 21 q.push(temp->left); 22 q.push(temp->right); 23 if(temp==NULL) dp[index++]=1000010; 24 else dp[index++]=temp->val; 25 } 26 for(int i=0;i<index;i++){ 27 if(i==0&&dp[i]==sum){ 28 count++; 29 }else if(dp[i]<=1000000&&dp[i]>=-1000000){ 30 dp[i]=dp[(i-1)/2]+dp[i]; 31 if(dp[i]==sum) count++; 32 } 33 } 34 return count; 35 } 36 };
想使用层序遍历+动态规划的方法O(n)完成,被NULL节点不能加入queue<TreeNode*> q给卡住了,之后再看看怎么改;对这种含有NULL多的怎么层序啊啊啊啊啊啊;
先看看大佬的方法:
python:非递归先序遍历+字典
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def pathSum(self,root,sum): 10 if root==None: 11 return 0 12 from collections import defaultdict 13 dictionary =defaultdict(int) 14 dictionary[0]=1 15 pNode,curr_sum,stack,res,prev=root,0,[],0,None 16 while(len(stack) or pNode): 17 if pNode: 18 curr_sum+=pNode.val 19 stack.append([pNode,curr_sum]) 20 dictionary[curr_sum]+=1 21 pNode=pNode.left 22 else: 23 pNode,curr_sum=stack[-1] 24 if pNode.right==None or pNode.right==prev: 25 res+=dictionary[curr_sum-sum] 26 if sum==0: 27 res-=1 28 dictionary[curr_sum]-=1 29 stack.pop() 30 prev=pNode 31 pNode=None 32 else: 33 pNode=pNode.right 34 return res 35
原文地址:https://www.cnblogs.com/joelwang/p/10453023.html
时间: 2024-09-30 12:02:27