二叉树中和为某一值的路径
来源:互联网 发布:js 瀑布流布局插件 编辑:程序博客网 时间:2024/06/05 11:28
题目描述:输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; }}
思路一:递归
import java.util.ArrayList;public class Solution { private ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>(); private ArrayList<Integer> list = new ArrayList<>(); public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { if (root == null) return listAll; list.add(root.val); target -= root.val; if (target == 0 && root.left == null && root.right == null) listAll.add(new ArrayList<Integer>(list)); FindPath(root.left, target); FindPath(root.right, target); list.remove(list.size() - 1); //移除最后一个元素,深度遍历完一条路径后要回退 return listAll; }}
思路二:非递归
1.按先序遍历把当前节点current的左孩子依次入栈同时保存当前节点,每次更新当前路径的和sum;
2.判断当前节点是否是叶子节点以及sum是否等于target,如果是,把当前路径放入结果中。
3.遇到叶子节点current更新为null,此时看栈顶元素,如果栈顶元素的右孩子为空或者为右孩子遍历过,把栈顶元素保存在last变量中,同时弹出栈顶元素,当前路径中去除该元素,sum减掉栈顶元素,这一步骤不更改current的值;
4.如果步骤3中的栈顶元素的右孩子存在且右孩子之前没有遍历过,当前节点current更新为栈顶的右孩子,此时改变current=null的情况。
import java.util.ArrayList;import java.util.Stack;public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList<ArrayList<Integer>> listAll = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> list = new ArrayList<>(); //当前路径 if (root == null) return listAll; Stack<TreeNode> stack = new Stack<>(); stack.push(root); int sum = 0; TreeNode current = root; //保存当前节点 TreeNode last = null; //保存上一个节点 while (!stack.isEmpty()) { if (current == null) { TreeNode temp = stack.peek(); if (temp.right != null && temp.right != last) current = temp.right; else { last = temp; stack.pop(); if (list.size() > 0) list.remove(list.size() - 1); sum -= temp.val; } } else { stack.push(current); sum += current.val; list.add(current.val); if (current.left == null && current.right == null && sum == target) listAll.add(new ArrayList<>(list));//如果不新添加一个ArrayList,list会一直变化 current = current.left; } } return listAll; }}
阅读全文
0 0
- 【树】二叉树中和为某一值的路径
- 【树6】二叉树中和为某一值的路径
- 题目11:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的所有路径
- 题目1368:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- 1368:二叉树中和为某一值的路径 @jobdu
- 二叉树中和为某一值的路径
- 二叉树中和为某一值的路径
- Q25:二叉树中和为某一值的路径
- 剑指offer:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径(剑指offer25)
- Visual Studio 快捷键
- 虚拟机1.图解虚拟机安装Mac系统
- Delphi Debug模式下可以但是Release模式下报错原因之一
- 程序员开发项目中7款可提高工作效率的几款工具!
- Android Studio 多版本地址切换
- 二叉树中和为某一值的路径
- U盘安装win7+centos7双系统
- POJ 2378 Tree Cutting——树形dp
- Makefile 详解一(含通用模板)
- Session 'app': Error Launching activity的解决方案
- 一个方法返回两个值
- Visual Studio下C++第三方库的配置方法总结
- 深度学习_BP神经网络
- boost::variant and boost::apply_visitor