echarts 漸變色進度條
阿新 • • 發佈:2020-10-29
給定一個二叉樹,它的每個結點都存放一個0-9的數字,每條從根到葉子節點的路徑都代表一個數字。
例如,從根到葉子節點路徑 1->2->3 代表數字 123。
計算從根到葉子節點生成的所有數字之和。
說明:葉子節點是指沒有子節點的節點。
示例 1:
輸入: [1,2,3]
1
/ \
2 3
輸出: 25
解釋:
從根到葉子節點路徑 1->2 代表數字 12.
從根到葉子節點路徑 1->3 代表數字 13.
因此,數字總和 = 12 + 13 = 25.
示例 2:輸入: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
輸出: 1026
解釋:
從根到葉子節點路徑 4->9->5 代表數字 495.
從根到葉子節點路徑 4->9->1 代表數字 491.
從根到葉子節點路徑 4->0 代表數字 40.
因此,數字總和 = 495 + 491 + 40 = 1026.來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/sum-root-to-leaf-numbers
第一版:使用字串,問題點:使用了額外的空間,字串
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution {private List<String> strArray = new ArrayList<>(); public int sumNumbers(TreeNode root) { dfs(root,""); int result = 0; if(strArray.size() > 0){ for(int i = 0; i < strArray.size();i++){ result = result + Integer.valueOf(strArray.get(i)); } }return result; } public String dfs(TreeNode node , String current){ if(node == null){ return ""; } current = current + node.val; if(node.left == null && node.right == null){ strArray.add(current); } if(node.left != null){ dfs(node.left,current); } if(node.right != null){ dfs(node.right,current); } return current; } }
更好的方法:
時間複雜度:O(n)
空間複雜度:O(n)
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int sumNumbers(TreeNode root) { return dfs(root,0); } public int dfs(TreeNode node , int current){ if(node == null){ return 0; } int result = current * 10 + node.val; //這是葉子節點 if(node.left == null && node.right == null){ return result; } return dfs(node.left,result) + dfs(node.right,result); } }