Given a binary tree and a sum, determine if the tree has a root-to-leaf path such this 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 / / / 4 / \ 7 2 1
Return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
Tags:tree Depth-first Search Solution 1:recursion
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: BOOLHaspathsum (treenode* root,intsum) { if(!root)return false; if(!root->left &&!root->Right ) { if(root->val==sum)return true; Else return false; } returnHaspathsum (Root->left, sum-(root->val)) | | Haspathsum (Root->right, sum-(root->val)); }};
Solution 2:stack
BOOLHaspathsum (treenode* root,intsum) { if(!root)return false; intCnt=root->Val; Stack<TreeNode*>Stk; Unordered_map<treenode*,BOOL>visited; Stk.push (root); Visited[root]=true; while(!Stk.empty ()) {TreeNode* top=Stk.top (); if(!top->left&&!top->Right ) { if(cnt==sum)return true; } if(top->left&&visited[top->left]==false) {Stk.push (top-Left ); Visited[top->left]=true; Cur+=top->left->Val; Continue; } if(top->right&&visited[top->right]==false) {Stk.push (top-Right ); Visited[top->right]=true; Cur+=top->right->Val; Continue; } stk.pop (); CNT-=top->Val; } return false;}
"Leetcode" 112-path Sum