面试题25. 二叉树中和为某一值的路径
来源:互联网 发布:整合网络推广方案ppt 编辑:程序博客网 时间:2024/06/06 02:07
题目描述
输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
思路:dfs
本题的考点是树的深搜,需要使用栈保存深搜的路径。同时使用set记录节点是否被访问过。
Java 代码:
import java.util.*;public class Solution { public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if(root == null) { return result; } Set<TreeNode> closed = new HashSet<>();//存放访问过的点 Stack<TreeNode> path = new Stack<>(); closed.add(root); path.push(root); int count = root.val; while(!path.isEmpty()) { TreeNode node = path.peek(); if(node.left != null && !closed.contains(node.left)) { closed.add(node.left); path.push(node.left); count += node.left.val; }else if(node.right != null && !closed.contains(node.right)) { closed.add(node.right); path.push(node.right); count += node.right.val; }else { if(node.left == null && node.right == null) { if(count == target) { ArrayList<Integer> r = new ArrayList<Integer>(); for(TreeNode n : path) { r.add(n.val); } result.add(r); } } count -= path.pop().val; } } return result; }}
Python 代码
# -*- coding:utf-8 -*-# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # 返回二维列表,内部每个列表表示找到的路径 def FindPath(self, root, expectNumber): result = [] if not root: return result visited = [root] path = [root] count = root.val while path: node = path[-1] if node.left and node.left not in visited: visited.append(node.left) path.append(node.left) count += node.left.val elif node.right and node.right not in visited: visited.append(node.right) path.append(node.right) count += node.right.val else: if not node.left and not node.right: if count == expectNumber: arr = [] for node in path: arr.append(node.val) result.append(arr) count -= path.pop().val return result
阅读全文
0 0
- 剑指offer-面试题25.二叉树中和为某一值的路径
- 面试题25. 二叉树中和为某一值的路径
- 二叉树经典面试题6~二叉树中和为某一值的路径
- 【IT笔试面试题整理】二叉树中和为某一值的路径--所有可能路径
- 面试题04 - 二叉树中和为某一值的所有路径 [树]
- 面试题25:二叉树中和为某一值的路径
- 面试题23:二叉树中和为某一值的路径
- 面试题25:二叉树中和为某一值的路径
- 【面试题二十五】二叉树中和为某一值的路径
- 【剑指offer】面试题25:二叉树中和为某一值的路径
- 二叉树中和为某一值的路径(面试题 25)
- 剑指Offer:面试题25 二叉树中和为某一值的路径
- 面试题25 二叉树中和为某一值的路径
- 剑指offer 面试题25 求二叉树中和为某一路径的值
- [程序员面试题精选100题]4.二叉树中和为某一值的所有路径
- 《剑指Offer》面试题25:二叉树中和为某一值的路径
- 剑指offer 面试题25—二叉树中和为某一值的路径
- 面试题25:二叉树中和为某一值的路径
- Leetcode 17. Letter Combinations of a Phone Number
- 程序员必须弄懂结构体,结构体基础知识
- linux下安装mxnet和python接口配置
- obc学习笔记2
- 1071. Speech Patterns (25)
- 面试题25. 二叉树中和为某一值的路径
- 玩转 Python 3.5 的 await/async
- Docker
- [leetcode]: 414. Third Maximum Number
- Wwise中ProLoadBank和PrepareEvent深入理解
- SQL语句中一些关键字的英文来源
- JAVA 异常
- 安装kalibr标定IMU
- Python进阶-装饰器