求根到叶子节点数字之和


前序遍历+判断

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res = 0;
    //List<String> res = new LinkedList<>();
    public int sumNumbers(TreeNode root) {
        if(root == null) return 0;
        preOrder(root,"");
        //for(int i=0;i<res.size();i++)
        //System.out.print(res.get(i)+" ");
        return res;
    }
    public void preOrder(TreeNode root,String tmp){
    if(root == null) return;
    tmp += root.val+"";
    if(root.left == null && root.right == null){
        res += Integer.parseInt(tmp);
        //res.add(tmp);
        tmp = tmp.substring(0,tmp.length()-1);
        return;
    }
    preOrder(root.left,tmp);
    preOrder(root.right,tmp);
    }
}

posted @ 2020-10-29 09:07  浅滩浅  阅读(151)  评论(0编辑  收藏  举报