leetcode--Path Sum II

本文介绍了一种使用后序遍历非递归算法解决寻找二叉树中所有路径和等于给定值的问题的方法,并提供了详细的Java实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]
]


题意:给定二叉树和一个sum,找出所有和为sum的路径

分类:二叉树


解法1:后序遍历非递归算法。每次访问一个节点,判断当前和是否和sum相等,如果是则保存这个路径。

[java]  view plain  copy
  1. /** 
  2.  * Definition for a binary tree node. 
  3.  * public class TreeNode { 
  4.  *     int val; 
  5.  *     TreeNode left; 
  6.  *     TreeNode right; 
  7.  *     TreeNode(int x) { val = x; } 
  8.  * } 
  9.  */  
  10. public class Solution {  
  11.     public List<List<Integer>> pathSum(TreeNode root, int target) {  
  12.         ArrayList<TreeNode> stack = new ArrayList<TreeNode>();    
  13.         List<List<Integer>> result = new ArrayList<List<Integer>>();    
  14.         int top = -1;    
  15.         int sum = 0;    
  16.         TreeNode p = root;          
  17.         do{             
  18.             while(p!=null){    
  19.                 top++;    
  20.                 sum += p.val;    
  21.                 stack.add(top,p);                   
  22.                 p = p.left;                 
  23.             }               
  24.             boolean flag = true;    
  25.             TreeNode q = null;    
  26.             while(top!=-1 && flag){    
  27.                 p = stack.get(top);    
  28.                 if(p.right==q){    
  29.                     if(p.left==null&&p.right==null && sum==target){    
  30.                         ArrayList<Integer> t = new ArrayList<Integer>();    
  31.                         for(TreeNode tNode : stack){    
  32.                             t.add(tNode.val);    
  33.                         }    
  34.                         result.add(t);    
  35.                     }    
  36.                     sum -= p.val;    
  37.                     stack.remove(top);    
  38.                     top--;    
  39.                     q = p;    
  40.                 }else{    
  41.                     p = p.right;    
  42.                     flag = false;                   
  43.                 }    
  44.             }    
  45.         }while(top!=-1);    
  46.         return result;    
  47.     }         

原文链接http://blog.youkuaiyun.com/xiaosongluo/article/details/52797156

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值