zoukankan      html  css  js  c++  java
  • 剑指offer-二叉树中某一路径的和为给定值

    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

    /**
     * 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
     * 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
     * 其实我一开始并没有想到先序遍历,而是用类似深搜的方法,不断地往下走,直到找到叶节点
     * 然后看sum是否与target相等
     * 但有个问题就是,遍历完某个结点的左孩子后,在遍历右孩子的时候,发现左孩子留了在list中。
     * 有一个办法就是在遍历之前再建立一个一模一样的list,这就是额外的空间消耗了。
     * 用先序遍历其实思路一样,但是用的是一个栈来维护,在遍历完某个结点的左右孩子后,需要将这个节点出栈。
     * @author admin
     *
     */
    public class PathSum {
    	public static ArrayList<ArrayList<Integer>> results=new ArrayList<ArrayList<Integer>>();
    	 public static ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
    	        if(root==null||target<root.val){
    	        	return results;
    	        }
    	        findPath(root,0,target,new ArrayList<Integer>());
    	        return results;
    	        
    	  }
    	 public static void findPath(TreeNode current,int sum,int target,ArrayList<Integer> stack){
    		 if(current!=null) {
    			 stack.add(current.val);
    			 sum+=current.val;
    			 if(current.left==null&&current.right==null) {
    				 if(sum==target){//如果sum==target则加进结果集中
    					 results.add(new ArrayList<Integer>(stack));
    				 }
    				 //如果不相等,也需要出栈,所以这里不return
    			 }
    			 if(current.left!=null){
    				 findPath(current.left,sum,target,stack);
    			 }
    			 if(current.right!=null){
    				 findPath(current.right,sum,target,stack);
    			 }
    			 //current结点出栈
    			 stack.remove(stack.size()-1);
    		 }
    	 }
    }
    

      

  • 相关阅读:
    DIY 作品 及 维修 不定时更新
    置顶,博客中所有源码 github
    openwrt PandoraBox PBR-M1 极路由4 HC5962 更新固件
    使用 squid 共享 虚拟专用网至局域网
    第一次参加日语能力测试 N5
    libx264 libfdk_aac 编码 解码 详解
    开发RTSP 直播软件 H264 AAC 编码 live555 ffmpeg
    MFC Camera 摄像头预览 拍照
    http2 技术整理 nginx 搭建 http2 wireshark 抓包分析 server push 服务端推送
    plist 图集 php 批量提取 PS 一个个切
  • 原文地址:https://www.cnblogs.com/qingfei1994/p/4900200.html
Copyright © 2011-2022 走看看