Sum Root to Leaf Numbers (LeetCode)
Question:
https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
解答:
没什么好说的。碰到树遍历的问题要不DFS,要不BFS, BFS可以递归或者Iterative。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { typedef pair<TreeNode*, int> TreePair; public: int sumNumbers(TreeNode *root) { if (!root) return 0; std::queue<TreePair> q; q.push(TreePair(root, root->val)); int sum = 0; while (!q.empty()) { TreePair& p = q.front(); TreeNode* leftChild = p.first->left; TreeNode* rightChild = p.first->right; if (!leftChild && !rightChild) { // found a leaf sum += p.second; } if (leftChild) q.push(TreePair(leftChild, p.second*10+leftChild->val)); if (rightChild) q.push(TreePair(rightChild, p.second*10+rightChild->val)); q.pop(); } return sum; } };