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

Leetcode#113Path Sum II

时间:2015-05-20 02:11:01      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:example   equals   public   where   

Path Sum II

 Total Accepted: 43473 Total Submissions: 162906My Submissions

Question Solution 


Given a binary tree and a sum, find all root-to-leaf paths where each path‘s sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             /             4   8
           /   /           11  13  4
         /  \    /         7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

分析:遍历树中的每一条路经,查看是否满足条件,采用栈数据结构


public class Solution {

    List<List<Integer>> x=new ArrayList<List<Integer>>();

    Stack<TreeNode> stack=new Stack<TreeNode>();

    

    void input(int s){

         List<Integer> y=new ArrayList<Integer>();

         

         Stack<TreeNode> mid=new Stack<TreeNode>();

         while(!stack.isEmpty())

         {

             TreeNode z=stack.peek();

             stack.pop();

             mid.push(z);

         }

         int sum=0;

         while(!mid.isEmpty())

         {

             TreeNode z=mid.peek();

             sum=sum+z.val;

             y.add(z.val);    

             mid.pop();

             stack.push(z);

         }

         if(sum==s)

            x.add(y);

    }

    

    public List<List<Integer>> pathSum(TreeNode root, int sum) {

        

        if(root==null)

            return x;

        else

        {

            stack.push(root);

            while(!stack.isEmpty())

            {

                TreeNode tn=stack.peek();

                if(tn.left!=null)

                {

                    stack.pop();

                    TreeNode mid=tn.left;

                    tn.left=null;

                    stack.push(tn);

                    stack.push(mid);

                }

                else if(tn.right!=null)

                {

                    stack.pop();

                    TreeNode mid=tn.right;

                    tn.right=null;

                    stack.push(tn);

                    stack.push(mid);

                }

                else

                {

                    input(sum);

                    while(!stack.isEmpty())

                    {

                        TreeNode v=stack.peek();

                        if(v.left==null&&v.right==null)

                            stack.pop();

                        else

                            break;

                    }

                }

                

            }

            return x;

        }

    }

}


Leetcode#113Path Sum II

标签:example   equals   public   where   

原文地址:http://7061299.blog.51cto.com/7051299/1652962

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