Given a binary tree containing digits from 0-9
only,
each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which
represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the
number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
這道題要我們找出從根節點到所有葉子節點的十進制數字的和,屬於很基礎的樹的遍歷題。
解法一:
使用DFS從根節點開始遍歷樹,在從上到下搜索過程中記錄當前十進制數字,當到達一個葉子節點時,累加到總和中。
遞歸問題要注意何時結束遞歸。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
sum = 0;
recursiveSum(root, 0);
return sum;
}
private:
int sum;
void recursiveSum(TreeNode *root, int curSum) {
if (NULL == root) {
return;
}
curSum = curSum * 10 + root->val;
if (NULL == root->left && NULL == root->right) {
sum += curSum;
}
recursiveSum(root->left, curSum);
recursiveSum(root->right, curSum);
}
};
解法二:
這樣的遍歷問題也可以使用非遞歸的方法,常用C++ queue容器存儲隊列元素,先進先出,從根節點遍歷過程中按層次把
節點信息加入隊列中,要注意到達葉子節點的操作。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumNumbers(TreeNode *root) {
if (NULL == root) {
return 0;
}
int sum = 0;
queue<NodeInfo> q;
q.push(NodeInfo(root->val, root));
while (!q.empty()) {
NodeInfo ni = q.front();
q.pop();
// when it is a left node
if (NULL == ni.nodePtr->left && NULL == ni.nodePtr->right) {
sum += ni.pathNum;
continue;
}
if (ni.nodePtr->left != NULL) {
q.push(NodeInfo(ni.pathNum * 10 + ni.nodePtr->left->val, ni.nodePtr->left));
}
if (ni.nodePtr->right != NULL) {
q.push(NodeInfo(ni.pathNum * 10 + ni.nodePtr->right->val, ni.nodePtr->right));
}
}
return sum;
}
private:
typedef struct NodeInfo {
int pathNum;
TreeNode *nodePtr;
NodeInfo(int _pathNum, TreeNode *_nodePtr) {
pathNum = _pathNum;
nodePtr = _nodePtr;
}
}NodeInfo;
};