《leetCode》:Sum Root to Leaf Numbers
제목
Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3 which represents the number 123.
Find the total sum of all root-to-leaf numbers.
For example,
    1
   / \
  2   3
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Return the sum = 12 + 13 = 25.생각
첫 번째 단계: 루트에서 잎 노드까지의 모든 경로를 찾아냅니다. 두 번째 단계: 구화
구현 코드는 다음과 같습니다.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */
public class Solution {
    private List<List<Integer>> res=new ArrayList<List<Integer>>();// 
    public int sumNumbers(TreeNode root) {
        if(root==null){
            return 0;
        }
        // : 
        sumNumbersHelper(root,new ArrayList<Integer>());
        // 
        return sumAllList(res);
    }
    private int sumAllList(List<List<Integer>> listList) {
        if(listList==null){
            return 0;
        }
        int sum=0;
        int listSum=0;
        for(List<Integer> temp:listList){
            listSum=0;// : 
            for(Integer num:temp){
                listSum=listSum*10+num;
            }
            sum+=listSum;
        }
        return sum;
    }
    private void sumNumbersHelper(TreeNode root,List<Integer> list) {
        if(root==null){
            return;
        }
        list.add(root.val);
        if(root.left==null&&root.right==null){// ,  
            res.add(list);
            return ;
        }
        else{
            sumNumbersHelper(root.left,new ArrayList<Integer>(list));
            sumNumbersHelper(root.right,new ArrayList<Integer>(list));
        }
    }
}작은 매듭
이 문제는 자신이 풀 수 없을 줄 알았는데, 쓰여져 있으면 생각이 트인다. 너무 흥미롭다. 하하
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 문자열 입력으로 모든 유효한 IP 주소 생성(LeetCode 93번 문제)이 문제의 공식 난이도는 Medium으로 좋아요 1296, 반대 505, 통과율 35.4%를 눌렀다.각 항목의 지표로 말하자면 보기에는 약간 규범에 맞는 것 같지만, 실제로도 확실히 그렇다.이 문제의 해법과 의도는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.