• NC_5_ALL_PATH_SUM


    package org.example.interview.practice;
    
    /**
     * @author xianzhe.ma
     * @date 2021/8/21
     */
    
    public class NC_5_ALL_PATH_SUM {
    
        public static int sumNumbers(TreeNode root) {
            // write code here
            if (root == null) return 0;
            return backtrack(root, 0);
        }
    
        public static int backtrack(TreeNode root, int sum) {
            if (root == null) return sum;
            // 加入当前结点的值
            sum = sum * 10 + root.val;
            if (root.left == null && root.right == null) {
                // 到叶子结点返回计算的值
                return sum;
            }
            // 未到叶子结点,则往左右子节点继续计算和
            return backtrack(root.left, sum) + backtrack(root.right, sum);
        }
    
        public static class TreeNode {
            int val = 0;
            TreeNode left = null;
            TreeNode right = null;
    
            public TreeNode(int val) {
                this.val = val;
            }
        }
    
        public static void main(String[] args) {
            TreeNode node0 = new TreeNode(4);
            TreeNode node1 = new TreeNode(1);
            TreeNode node2 = new TreeNode(2);
            node0.right = node1;
            node0.left = node2;
            int result = sumNumbers(node0);
            System.out.println(result);
    
        }
    }
  • 相关阅读:
    离愁
    梦想与生活
    神秘巨星
    Web用户控件
    Ajax
    php的基本语法与字符串与增删改查
    php建立方法
    jquery
    上传文件
    webfrom验证控件
  • 原文地址:https://www.cnblogs.com/juniorMa/p/15879363.html
Copyright © 2020-2023  润新知