Sum Root to Leaf Numbers

Sum Root to Leaf Numbers

  Total Accepted: 26533  Total Submissions: 89186 My Submissions
Question  Solution 

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;
};


你可能感兴趣的:(Sum Root to Leaf Numbers)