首页 > 试题广场 >

二叉树根节点到叶子节点的所有路径和

[编程题]二叉树根节点到叶子节点的所有路径和
  • 热度指数:78312 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个二叉树的根节点root,该树的节点值都在数字 之间,每一条从根节点到叶子节点的路径都可以用一个数字表示。
1.该题路径定义为从树的根结点开始往下一直到叶子结点所经过的结点
2.叶子节点是指没有子节点的节点
3.路径只能从父节点到子节点,不能从子节点到父节点
4.总节点数目为n

例如根节点到叶子节点的一条路径是,那么这条路径就用 来代替。
找出根节点到叶子节点的所有路径表示的数字之和
例如:

这颗二叉树一共有两条路径,
根节点到叶子节点的路径 用数字 代替
根节点到叶子节点的路径 用数字 代替
所以答案为

数据范围:节点数 ,保证结果在32位整型范围内
要求:空间复杂度 ,时间复杂度
进阶:空间复杂度 ,时间复杂度 
示例1

输入

{1,2,3}

输出

25
示例2

输入

{1,0}

输出

10
示例3

输入

{1,2,0,3,4}

输出

257

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
推荐
先序遍历的思想(根左右)+数字求和(每一层都比上层和*10+当前根节点的值)

	public int sumNumbers(TreeNode root) {
		int sum = 0;
		if (root == null) {
			return sum;
		}
		return preorderSumNumbers(root, sum);
	}
	public int preorderSumNumbers(TreeNode root, int sum) {
		if (root == null)
			return 0;
		sum = sum * 10 + root.val;
		if (root.left == null && root.right == null) {
			return sum;
		}
		return preorderSumNumbers(root.left, sum) + preorderSumNumbers(root.right, sum);
	}

编辑于 2016-12-03 17:32:39 回复(19)
int ans = 0; 
    public int sumNumbers (TreeNode root) {
        // write code here
        if (root == null) {
            return ans;
        }
        int path = 0;
        process(root, path);
        return ans;
    }

    private void process(TreeNode root, int path) {
        path = path * 10 + root.val;
        if (root.left == null && root.right == null) {
            ans += path;
            return;
        }
        
        if (root.left != null) {
            process(root.left, path);
        }
        if (root.right != null) {
            process(root.right, path);
        }
    }

发表于 2023-08-26 16:00:39 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        ArrayList<ArrayList<Integer>> allPath = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> path  = new ArrayList<Integer>();
        if (root == null) {
            return 0;
        }
        path.add(root.val);
        if (root.left == null && root.right == null) {
            allPath.add(new ArrayList<Integer>(path));
        } else {
            findAllPath(allPath, path, root.left);
            findAllPath(allPath, path, root.right);
        }
        int pathSum = allPath.stream().filter(list->list != null &&
        list.size() > 0).mapToInt(list-> {
            int sum = 0;
            for (int idx = 0; idx < list.size(); idx++) {
                sum += list.get(idx) * Math.pow(10, list.size() - 1 - idx);
            }
            return sum;
        }).sum();
        return pathSum;
    }

    public void findAllPath(ArrayList<ArrayList<Integer>> allPath,
                            ArrayList<Integer> path, TreeNode node) {
        if (node == null) {
            return;
        }
        path.add(node.val);
        if (node.left == null && node.right == null) {
            allPath.add(new ArrayList<Integer>(path));
        } else {
            findAllPath(allPath, path, node.left);
            findAllPath(allPath, path, node.right);
        }
        path.remove(path.size() - 1);
        return;
    }
}

发表于 2023-05-08 09:51:25 回复(0)
回溯法每次遍历路径记录,lists存所有路径,然后从每一个叶子结点加起,其父节点*10,以此类推,直至加到根节点,再加下一条路径的值
public int sumNumbers (TreeNode root) {
        ArrayList<Integer>list = new ArrayList<>();
        ArrayList<ArrayList<Integer>>lists = new ArrayList<>();
        dfs(root, list, lists);
        int sum = 0;
        for (int i = 0; i < lists.size(); i++) {
            int n = 1;
            ArrayList<Integer>newlist = new ArrayList<>();
            for (int j = 0; j < lists.get(i).size(); j++) {
                int num = lists.get(i).get(lists.get(i).size() - j - 1) * n;
                sum += num;
                n = 10 * n;
            }
        }
        return sum;
    }
    public void dfs(TreeNode root, ArrayList<Integer>list,
                    ArrayList<ArrayList<Integer>>lists) {
        if (root == null) {
            return;
        }
        if (root.left != null || root.right != null) {
            list.add(root.val);
            dfs(root.left, list, lists);
            dfs(root.right, list, lists);
            list.remove(list.size()-1);
        }
        if (root.left == null && root.right == null) {
            list.add(root.val);
            lists.add(new ArrayList<>(list));
            list.remove(list.size() - 1);
        }
    }

发表于 2022-10-17 16:24:56 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     *
     * @param root TreeNode类
     * @return int整型
     */
    int res = 0;
    public int sumNumbers (TreeNode root) {
        // write code here
        if (root == null) return 0;

        dfs(root, 0);

        return res;
    }

    public void dfs(TreeNode t, int sum) {
        if (t == null) return;
        if (t.left == null && t.right == null) {
            res = res + t.val + sum * 10;
            return;
        }
        dfs(t.left, sum * 10 + t.val);
        dfs(t.right, sum * 10 + t.val);
    }
}

发表于 2022-09-04 10:17:03 回复(0)
感觉自己像个rz,我是怎么想起来先把所有路径都遍历出来,再去求值的。。
public class Solution {
    
    List<List<Integer>> lists = new LinkedList<>();
    Deque queue = new LinkedList<>();
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        //dfs
        dfs(root);
        int n = 0;
        for (int i=0;i<lists.size();i++) {
            List<Integer> list = lists.get(i);
            String num = "";
            for (int j=0;j<list.size();j++) {
                num = num + list.get(j);
            }
            n = n + Integer.parseInt(num);
        }
        return n;
            
    }
    public void dfs(TreeNode root) {
        
        if(root == null) {
            return;
        }
        queue.offerLast(root.val);
        if (root.left == null && root.right == null) {
            lists.add(new LinkedList<>(queue));
        }
        dfs(root.left);
        dfs(root.right);
        queue.pollLast();
    }
}
发表于 2022-06-07 18:07:28 回复(0)
public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    private int result = 0;
    public int sumNumbers (TreeNode root) {
        // write code here
        int num = 0;
        dfs(root,num);
        return result;
    }
    
    private void dfs(TreeNode root,int num){
        if(root == null){
            return;
        }
        num = num * 10 + root.val;
        if(root.left==null && root.right==null){
             result = result + num;
        }
        dfs(root.left,num);
        dfs(root.right,num);
        num = (num - root.val)/10;
    }
}
发表于 2022-06-05 18:53:47 回复(0)
dfs,先序遍历的思想
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        if(root==null) return 0;
        List<Integer> nums=new LinkedList<>();
        
        dfs(root,root.val,nums);
        int ans=0;
        for(int i=0;i<nums.size();i++) ans+=nums.get(i);
        return ans;
    }
    
    void dfs(TreeNode root,int curVal,List<Integer> nums){
        // 根节点
        if(root.left==null&&root.right==null){
            nums.add(curVal);
            return ;
        }
        
        if(root.left!=null){
            dfs(root.left,curVal*10+root.left.val,nums);
        }
        if(root.right!=null){
            dfs(root.right,curVal*10+root.right.val,nums);
        }
        return ;
    }
}


发表于 2022-05-10 21:55:27 回复(0)
public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        if(root == null)  return 0;
        int res = 0;
        return dfs(root, res);

    }
    public int dfs(TreeNode t, int res){
        if(t == null)  return 0;
        if(t.left == null && t.right == null){
            return res * 10 + t.val;
        }
        return dfs(t.left, res*10 + t.val) + dfs(t.right, res*10 + t.val);
    }
}
dfs遍历求和
发表于 2022-04-15 10:58:43 回复(0)
import java.util.*;

public class Solution {
    public int sumNumbers (TreeNode root) {
        return dfs(root, 0);
    }
    public int dfs (TreeNode root, int temp) {
        if (root == null) {
            return 0;
        }
        temp = temp * 10 + root.val;
        if (root.left == null && root.right == null) return temp;
        return dfs(root.left, temp) + dfs(root.right, temp);
    }
}

发表于 2022-02-12 22:33:58 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    ArrayList<ArrayList<Integer>> res=new ArrayList<>();
    ArrayList<Integer> path=new ArrayList<>();
    public int sumNumbers (TreeNode root) {
        // write code here
         backtrace(root);
        int resNum=0;
        for(ArrayList<Integer> tem:res){
            int cur=0;
            for(int i=0;i<tem.size();i++){
                cur=cur*10+tem.get(i);
            }
            resNum+=cur;
        }
        return resNum;
    }
    public void backtrace(TreeNode root){
        //base case
        if(root==null) return;
        //将根加到path中
        path.add(root.val);
        //sum-=root.val;
        //因为要到叶子节点
        if(root.left==null&&root.right==null){
            //符合条件
            res.add(new ArrayList(path));
        }
        backtrace(root.left);
        backtrace(root.right);
        //路径恢复,将当前节点从路径中移除
        path.remove(path.size()-1);
        
    }
}

发表于 2022-01-29 09:57:13 回复(0)

没想到这么简单

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
      int res=0;
    public int sumNumbers (TreeNode root) {
         if(root==null) return 0;
        dfs(root,0);
        return res;
    }
    public void dfs(TreeNode root,int val){
        if(root==null) return;
        val=val*10+root.val;
        if(root.left==null&&root.right==null) res+=val;
        dfs(root.left,val);
        dfs(root.right,val);
    }
}
发表于 2021-12-26 09:55:12 回复(0)
public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode treeNode) {
        // write code here
        List<Integer> pathList = new ArrayList<>();
        getNumber(treeNode, "", pathList);
        if (pathList.size() == 0) {
            return 0;
        }
        return pathList.get(0);
    }
    
    private void getNumber(TreeNode node, String path, List<Integer> pathValue) {
        if (node == null) {
            return;
        }
        path += node.val;
        getNumber(node.left, path, pathValue);
        getNumber(node.right, path,pathValue);
        if (node.left == null && node.right == null) {
            if (pathValue.size() == 0) {
                pathValue.add(Integer.valueOf(path));
            } else {
                pathValue.set(0, pathValue.get(0) + Integer.valueOf(path));
            }
        }
    }
}

发表于 2021-12-12 01:57:43 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        if(root==null) return 0;
        Stack<TreeNode> nodeStack=new Stack<>();
        Stack<Integer> valueStack=new Stack<>();
        int res=0;
        nodeStack.add(root);
        valueStack.add(root.val);
        while(!nodeStack.isEmpty()){
            TreeNode node=nodeStack.pop();
            int value=valueStack.pop();
            if(node.left==null&&node.right==null){
                res+=value;
            }else{
                if(node.left!=null){
                    nodeStack.push(node.left);
                    valueStack.push(value*10+node.left.val);
                }
                if(node.right!=null){
                    nodeStack.push(node.right);
                    valueStack.push(value*10+node.right.val);
                }
            }
        }
        return res;
    }
}

发表于 2021-11-30 19:10:55 回复(0)
public class Solution {
    public int sumNumbers (TreeNode root) {
        if (root == null) return 0;
        ArrayList<String> res = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        dfs(root, sb, res);
        int sum = 0;
        for (int i = 0; i < res.size(); i++)
            sum = sum + Integer.parseInt(res.get(i));
        return sum;
    }
    void dfs(TreeNode root, StringBuffer sb, ArrayList<String> res){
        sb.append(root.val);
        if (root.left == null && root.right == null)
            res.add(sb.toString());
        if (root.left != null)
            dfs(root.left, sb, res);
        if (root.right != null)
            dfs(root.right, sb, res);
        sb.deleteCharAt(sb.length() - 1);        
    }   
}
先做了NC8,这题就很简单了
发表于 2021-11-19 20:42:31 回复(0)
回溯
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        List<String> res = new ArrayList<>();
        dfs(root,new StringBuilder(),res);
        //System.out.println(res);
        int sum = 0;
        for (String re : res) {
            sum+=Integer.parseInt(re);
        }
        return sum;
    }

    public void dfs(TreeNode root, StringBuilder track, List<String> res) {
        if (root==null) return;
        if (root.left==null && root.right==null) {
            track.append(root.val);
            res.add(track.toString());
            removeLast(track);
            return;
        }
        track.append(root.val);
        if (root.left!=null) dfs(root.left,track,res);
        if (root.right!=null) dfs(root.right,track,res);
        // 回溯
        removeLast(track);
    }

    // 将 StringBuilder 的最后一个元素移除,方便后面的回溯操作
    private static void removeLast(StringBuilder sb) {
        sb.replace(sb.length()-1,sb.length(),"");
    }
}


发表于 2021-11-02 15:58:47 回复(0)
直接dfs一把梭
public class Solution {
    
    int res = 0;
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        if (root == null) return res;
        if (root.left == null && root.right == null) return root.val;
        
        dfs(root, 0);
        return res;
    }
    
    public void dfs(TreeNode root, int n) {
        if (root.left == null && root.right == null) {
            res += n * 10 + root.val;
            return;
        }
        
        n = n * 10 + root.val;
        if (root.left != null) dfs(root.left, n);
        if (root.right != null) dfs(root.right, n);
    }
}


发表于 2021-09-17 22:19:12 回复(0)
import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int count=0;
    public int sumNumbers (TreeNode root) {
        if(root==null) return 0;
        if(root.left==null && root.right==null) {
            count=count+root.val;
        }
        if(root.left!=null){
            root.left.val=root.val*10+root.left.val; 
            sumNumbers(root.left);
        }
        if(root.right!=null){
            root.right.val=root.val*10+root.right.val;
            sumNumbers(root.right);
        }
        return count;
        
        // write code here
    }
}
发表于 2021-08-31 20:09:41 回复(0)
public class Solution {
    public int sum=0;
    public int temp=0;
    public int sumNumbers (TreeNode root) {
        dfs(root);
        return sum;
    }
    public void dfs(TreeNode root){
        if(root==null) return;
        temp = temp*10 + root.val;
        //叶子节点,收集结果
        if(root.left==null&&root.right==null) sum+=temp;
        //递归
        dfs(root.left);
        dfs(root.right);
        //回溯
        temp = temp/10;
    }
}

发表于 2021-08-31 18:56:45 回复(0)
import java.util.*;
public class Solution {
    ArrayList<StringBuilder> ansList = new ArrayList<>();
    public int sumNumbers (TreeNode root) {
        StringBuilder path = new StringBuilder();
        curVisitPath(root,path);
        int result = 0;
        for(StringBuilder sb : ansList)
            result += new Integer(sb.toString());
        return result;
    }
    
    public void curVisitPath (TreeNode root, StringBuilder path) {
        if(root == null)
            return;
        if(root.left == null && root.right == null) {
            path.append(root.val);
            ansList.add(new StringBuilder(path));
            path.delete(path.length() - 1, path.length());
            return;
        }
        path.append(root.val);
        curVisitPath(root.left,path);
        curVisitPath(root.right,path);
        path.delete(path.length() - 1, path.length());
    }
}

发表于 2021-08-31 11:22:27 回复(0)

问题信息

难度:
59条回答 33535浏览

热门推荐

通过挑战的用户