当前位置:网站首页>Leetcode-129- sum of numbers from root node to leaf node

Leetcode-129- sum of numbers from root node to leaf node

2022-06-11 21:27:00 z754916067

subject

  1. Find the sum of numbers from root node to leaf node
    Give you the root node of a binary tree root , Each node in the tree stores a 0 To 9 Number between .
    Each path from the root node to the leaf node represents a number :

for example , Path from root node to leaf node 1 -> 2 -> 3 Representation number 123 .
Calculates the generated from the root node to the leaf node The sum of all the figures .

Leaf nodes A node without children .
 Insert picture description here

Ideas

  1. One glance recursion , How do binary trees always recurse , It's a bit of a backtrack .
  2. It's quite simple , If binary tree recursion is too much, it will become familiar .

Code

    int sum=0;
    public int sumNumbers(TreeNode root) {
    
        if(root.left==null && root.right==null) return root.val;
        // recursive   Record the current number 
        // The root node 
        int val = root.val;
        LinkedList<Integer> ll = new LinkedList<>();
        ll.add(val);
        if(root.left!=null) DFS(root.left,ll);
        if(root.right!=null) DFS(root.right,ll);

        return sum;
    }
    public void DFS(TreeNode root,LinkedList<Integer> ll){
    
        // Go to the leaf node to indicate that the calculation is ready 
        if(root.left==null && root.right==null){
    
            ll.add(root.val);
            int temp=0;
            int nums=1;
            for(int i=ll.size()-1;i>=0;i--){
    
                temp+=ll.get(i)*nums;
                nums*=10;
            }
            sum+=temp;
            ll.removeLast();
            return;
        }
        // otherwise   Add it to ll
        ll.add(root.val);
        if(root.left!=null) DFS(root.left,ll);
        if(root.right!=null) DFS(root.right,ll);
        ll.removeLast();
        return;
    }

原网站

版权声明
本文为[z754916067]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206112122431103.html