package com.算法专练.力扣.从根到叶的二进制数之和;
import java.util.ArrayList;
import java.util.List;
/**
* @author xnl
* @Description:
* @date: 2022/5/30 21:28
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
TreeNode root = new TreeNode(1, new TreeNode(0, new TreeNode(0), new TreeNode(1)),
new TreeNode(1, new TreeNode(0), new TreeNode(1)));
System.out.println(solution.sumRootToLeaf(root));
}
public int sumRootToLeaf(TreeNode root) {
int ans = 0;
if (root == null){
return ans;
}
List<String> list = new ArrayList<>();
dfs(root, "", list);
for (String str : list){
ans += binaryToTen(str);
}
return ans;
}
/**
* 二进制转十进制
* @return
*/
private int binaryToTen(String binary){
int length = binary.length() - 1, i = 0;
int result = 0;
while (i <= length){
result += (binary.charAt(i) -'0') << (length - i++);
}
return result;
}
/**
* 所有符合结果的数
* @param node 节点
* @param str 结果
* @param list 存放结果的容器
*/
private void dfs(TreeNode node, String str, List<String> list){
if (node.left != null){
dfs(node.left, str + node.val, list);
}
if (node.left == null && node.right == null){
list.add(str + node.val);
}
if (node.right != null){
dfs(node.right, str + node.val, list);
}
}
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
力扣:1022. 从根到叶的二进制数之和
最新推荐文章于 2024-08-13 21:21:03 发布