zoukankan      html  css  js  c++  java
  • 算法-01-二叉树根节点到叶子节点和为指定值的路径

    描述

    给定一个二叉树和一个值sum,请找出所有的根节点到叶子节点的节点值之和等于sum 的路径, 例如: 给出如下的二叉树,sum=22

    Java 

    import java.util.*;
    
    /*
     * public class TreeNode {
     *   int val = 0;
     *   TreeNode left = null;
     *   TreeNode right = null;
     * }
     */
    
    public class Solution {
        /**
         * 
         * @param root TreeNode类 
         * @param sum int整型 
         * @return int整型ArrayList<ArrayList<>>
         */
        ArrayList<ArrayList<Integer>> results= new ArrayList<>();
        
        public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
            // write code here
            ArrayList<Integer> path =new ArrayList<>();
            if(root==null)
                return results;
            dfs(root,0,sum,path);
            return results;
        }
        
        public void dfs(TreeNode root,int nowSum, int sum, ArrayList<Integer> list){
            list.add(root.val);
            if(root.right==null&&root.left==null&&sum==nowSum+root.val){
                results.add(new ArrayList<>(list));
                return;
            }
            if(root.left!=null){
                dfs(root.left,nowSum+root.val,sum,list);
                list.remove(list.size()-1);
            }
            if(root.right!=null){
                dfs(root.right, nowSum+root.val,sum,list);
                list.remove(list.size()-1);
            }
        }
    }

     Python 

    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    #
    # 
    # @param root TreeNode类 
    # @param sum int整型 
    # @return int整型二维数组
    #
    class Solution:
        def pathSum(self , root , sum ):
            # write code here
            path = []
            paths = []
            self.dfs(root,sum,path,paths)
            return paths
            
        def dfs(self, root: TreeNode, sum :int, path: list, paths: list):
            if root is None:
                return None
            path.append(root.val)
            if root.left is None and root.right is None and sum==root.val:
                paths.append(path.copy())
            else:
                self.dfs(root.left,sum-root.val,path,paths)
                self.dfs(root.right,sum-root.val,path,paths)
            path.pop(len(path)-1)
      
    不要小瞧女程序员
  • 相关阅读:
    LiLicense server OR Activation code
    一个比喻讲明Docker是什么
    Linux 系统目录结构说明
    Sublime Text2支持Vue语法高亮显示
    javascript权威指南笔记[6-8]
    javascript权威指南笔记[1-5]
    使用chrome控制台调试js代码
    windows与linux下执行.class(包含main方法)
    linux 命令
    几种常见的编码格式
  • 原文地址:https://www.cnblogs.com/shix0909/p/15028414.html
Copyright © 2011-2022 走看看