[LeetCode] Path Sum

來源:互聯網
上載者:User

標籤:

This problem has a very easy recursive code as follows.

 1 class Solution { 2 public: 3     bool hasPathSum(TreeNode* root, int sum) { 4         if (!root) return false; 5         if (!(root -> left) && !(root -> right)) 6             return sum == root -> val; 7         return hasPathSum(root -> left, sum - root -> val) || 8                hasPathSum(root -> right, sum - root -> val); 9     }10 };

If you insist on an iterative solution, this link has a clean iterative solution in Python. I rewrite the code in C++ as follows. In fact, it uses pair<TreeNode*, int> to recor the information, which greatly simplifies the code.

 1 class Solution { 2 public: 3     bool hasPathSum(TreeNode* root, int sum) { 4         if (!root) return false; 5         stack<pair<TreeNode*, int> > pairs; 6         pairs.push(make_pair(root, sum)); 7         while (!pairs.empty()) { 8             pair<TreeNode*, int> pr = pairs.top(); 9             pairs.pop();10             TreeNode* node = pr.first;11             int remain = pr.second;12             if (!(node -> left) && !(node -> right) && remain == node -> val)13                 return true;14             if (node -> left)15                 pairs.push(make_pair(node -> left, remain - node -> val));16             if (node -> right)17                 pairs.push(make_pair(node -> right, remain - node -> val));18         }19         return false;20     }21 };

This link gives a longer iterative solution using postorder traversal.

 1 class Solution { 2 public: 3     bool hasPathSum(TreeNode* root, int sum) { 4         TreeNode* pre = NULL; 5         TreeNode* cur = root; 6         stack<TreeNode*> nodes; 7         int s = 0; 8         while (cur || !nodes.empty()) { 9             while (cur) {10                 nodes.push(cur);11                 s += cur -> val;12                 cur = cur -> left;13             }14             cur = nodes.top();15             if (!(cur -> left) && !(cur -> right) && s == sum)16                 return true;17             if (cur -> right && pre != cur -> right)18                 cur = cur -> right;19             else {20                 pre = cur;21                 nodes.pop();22                 s -= cur -> val;23                 cur = NULL;24             }25         }26         return false;27     }28 };

 

[LeetCode] Path Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.