面试题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
原创粉丝点击