二叉树根节点到叶子节点的所有路径和


package com.shence;
import org.junit.Test;

import java.util.*;
public class Solution {
    class TreeNode {
        int val;
        TreeNode(int val) {
            this.val = val;
        }
        TreeNode left = null;
        TreeNode right = null;
    }
    StringBuilder sb;
    int res;
    public int sumNumbers (TreeNode root) {
        if(root == null) return 0;
        sb = new StringBuilder();
        res = 0;
        solve(root);
        return res;
    }
    public void solve(TreeNode root) {
        if(root == null) return;
        sb.append(root.val);
        if(root.left == null && root.right == null)
            res += Integer.valueOf(sb.toString());
        if(root.left != null) solve(root.left);
        if(root.right != null) solve(root.right);
        sb.deleteCharAt(sb.length()-1);
    }
    @Test
    public void test() {
        TreeNode n1 = new TreeNode(1);
        TreeNode n2 = new TreeNode(2);
        TreeNode n3 = new TreeNode(3);
        n1.left = n2;
        n1.right = null;
        System.out.println(sumNumbers(n1));
    }
}
posted @ 2020-09-30 14:13  li修远  阅读(507)  评论(0编辑  收藏  举报