leetcode 129. Sum Root to Leaf Numbers 一个简单的DFS做法 + 注意递归结束条件

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深度优先遍历。

注意对叶子节点的判断。

代码如下:

import java.util.ArrayList;
import java.util.List;

/*class TreeNode 
{
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
}*/

public class Solution 
{
    int sum=0;
    public int sumNumbers(TreeNode root) 
    {
        List one=new ArrayList();
        byRecursion(root,one);
        return sum;
    }

    //递归获取路径
    void byRecursion(TreeNode root,List one) 
    {
        if(root==null)
            return ;    
        else
        {
            if(root.left==null && root.right==null)
            {
                one.add(root);
                int tmp=0;
                for(int i=0;i10 +one.get(i).val;
                sum+=tmp;
                one.remove(one.size()-1);
            }
            if(root.left!=null)
            {
                one.add(root);
                byRecursion(root.left, one);
                one.remove(one.size()-1);
            }
            if(root.right!=null)
            {
                one.add(root);
                byRecursion(root.right, one);
                one.remove(one.size()-1);
            }
        }
    }
}

下面是C++的做法,就是做一个DFS深度优先遍历的做法

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

/*
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
*/

class Solution
{
public:
    int sum = 0;
    int sumNumbers(TreeNode* root)
    {
        if (root == NULL)
            return 0;
        vector<int> one;
        getAll(root, one);
        return sum;
    }

    void getAll(TreeNode* root, vector<int> one)
    {
        if (root == NULL)
            return;
        else
        {
            one.push_back(root->val);
            if (root->left == NULL && root->right == NULL)
            {
                int tmp = 0;
                for (int i = 0; i < one.size(); i++)
                    tmp = 10 * tmp + one[i];
                sum += tmp;
            }
            if (root->left != NULL)
                getAll(root->left, one);
            if (root->right != NULL)
                getAll(root->right, one);
            one.erase(one.end()-1);
        }
    }
};

你可能感兴趣的:(leetcode,For,Java,DFS深度优先搜索,需要好好想一下的题目,leetcode,For,C++)