码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树中和为某一值的所有路径

时间:2017-05-06 22:59:28      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:使用   get   logs   迭代   public   array   java   treenode   new   

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

import java.util.ArrayList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,
            int target) {
        ArrayList<ArrayList<Integer>> pathList = new ArrayList<ArrayList<Integer>>();
        if(root==null)
            return pathList;
        Stack<Integer> stack=new Stack<Integer>();
        FindPath(root,target,stack,pathList);
        return pathList;
         
    }
    private void FindPath(TreeNode root, int target,
            Stack<Integer> path,
            ArrayList<ArrayList<Integer>> pathList) {
        if(root==null)
            return;
        //如果是叶子节点
        if(root.left==null&&root.right==null){
            if(root.val==target){//如果叶子节点上的值正好等于target的值
                ArrayList<Integer> list=new ArrayList<Integer>();
                for(int i:path){
                    list.add(new Integer(i));
                }
                list.add(new Integer(root.val));
                pathList.add(list);
            }
        }
        else{//如果不是叶子节点继续往下迭代,一直迭代到叶子节点。
            path.push(new Integer(root.val));
            FindPath(root.left, target-root.val, path, pathList);
            FindPath(root.right, target-root.val, path,  pathList);
            //如果走到这里说明走到左右子节点都不满足,所以需要向上移动一个节点
            //所以使用path.pop()
            path.pop();
        }
         
    }
}

 

二叉树中和为某一值的所有路径

标签:使用   get   logs   迭代   public   array   java   treenode   new   

原文地址:http://www.cnblogs.com/LoganChen/p/6818675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!