zoukankan      html  css  js  c++  java
  • 二叉树根节点到叶子节点的所有路径和

    
    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));
        }
    }
    
  • 相关阅读:
    NOIP2018游记-DAY1
    NOIP2018游记-DAY0
    18.11.7绍一模拟赛
    [SPOJ]SELTEAM
    18.11.5绍一模拟赛
    18.11.2绍一模拟赛
    [模拟赛]世界杯
    [模拟赛]路途
    乘法逆元的研究
    子查询,TOP_N,分页,行转列
  • 原文地址:https://www.cnblogs.com/lixyuan/p/13754294.html
Copyright © 2011-2022 走看看