LeetCode -- Path Sum III分析及实现方法
题目描述:
You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes). The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
给定一个二叉树,遍历过程中收集所有可能路径的和,找出和等于X的路径树。
思路:
设当前节点为root,分别收集左右节点路径和的集合,merge到当前集合中;
将当前节点添加到数组中,构成新的可能路径。
实现代码:
/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { private int _sum; private int _count; public int PathSum(TreeNode root, int sum) { _count = 0; _sum = sum; Travel(root, new List()); return _count; } private void Travel(TreeNode current, List ret){ if(current == null){ return ; } if(current.val == _sum){ _count ++; } var left = new List (); Travel(current.left, left); var right = new List (); Travel(current.right, right); ret.AddRange(left); ret.AddRange(right); for(var i = 0;i < ret.Count; i++){ ret[i] += current.val; if(ret[i] == _sum){ _count ++; } } ret.Add(current.val); //Console.WriteLine(ret); } }
茶杯头甜蜜终章dlc 官方手机版v1.0.0.3
下载火柴人传说暗影格斗内置菜单 最新版v3.0.1
下载荒野乱斗测试服 安卓版v61.10.3
下载荒野乱斗彩虹服 安卓版v61.10.3
下载寒霜启示录 安卓版v1.25.10
寒霜启示录是一款生存模拟游戏,不少玩家可能对于末日都有着自己
末日城堡免广告版 安卓最新版v0.7.1
末日城堡免广告版是一款非常好玩的模拟经营类游戏,内部可以不看
甜蜜人生模拟器 最新版v1.4.5
甜蜜人生模拟器是一款非常好玩的模拟恋爱手游,玩家在这里能够对
武器锻造师内置功能菜单 v10.4
武器锻造师内置菜单版是游戏的破解版本,在该版本中为玩家提供了
开放空间overfield 安卓版v1.0.5
开放空间Overfield是一款箱庭养成经营手游,让你在广阔