博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
二叉树中和为某一值的路径
阅读量:4187 次
发布时间:2019-05-26

本文共 2140 字,大约阅读时间需要 7 分钟。

1.  先序遍历的思想

正向思路:

public ArrayList
> FindPath(TreeNode root, int target) { ArrayList
> all = new ArrayList
>(); // 先对二叉树的情况进行判断 if (root == null) return all; // 存放每一轮的搜索结果 ArrayList list = new ArrayList
(); int sum = 0; dfs(root, target, all, list, sum); return all; } public void dfs(TreeNode root, int target, ArrayList
> all, ArrayList
list, int sum) { if (root == null) // 树为空 return ; sum += root.val; list.add(root.val); // 搜索到叶节点并且满足题目条件 if (root.left == null && root.right == null && sum == target) { all.add(new ArrayList
(list)); list.remove(list.size()-1); // 移除最后一个元素 return; } // 继续遍历左子树 dfs(root.left, target, all, list, sum); // 继续遍历右子树 dfs(root.right, target, all, list, sum); list.remove(list.size()-1); }
public ArrayList
> FindPath(TreeNode root, int target) { ArrayList
> all = new ArrayList
>(); // 先对二叉树的情况进行判断 if (root == null) return all; // 存放每一轮的搜索结果 ArrayList list = new ArrayList
(); int sum = 0; dfs(root, target, all, list, sum); return all; } public void dfs(TreeNode root, int target, ArrayList
> all, ArrayList
list, int sum) { if (root == null) // 树为空 return ; sum += root.val; list.add(root.val); // 搜索到叶节点并且满足题目条件 if (root.left == null && root.right == null && sum == target) { all.add(new ArrayList
(list)); } // 继续遍历左子树 if (root.left != null) dfs(root.left, target, all, list, sum); // 继续遍历右子树 if (root.right != null) dfs(root.right, target, all, list, sum); list.remove(list.size()-1); }

另一种思路:

private ArrayList
> all = new ArrayList
>(); // 存放最终结果 private ArrayList
list = new ArrayList
(); // 存放每一轮的结果 public ArrayList
> FindPath(TreeNode root, int target) { // 先对二叉树的情况进行判断 if (root == null) // 树为空 return all; list.add(root.val); target -= root.val; // 搜索到叶节点并且满足题目条件 if (target == 0 && root.left == null && root.right == null) all.add(new ArrayList<>(list)); // 继续遍历左子树 FindPath(root.left, target); // 继续遍历右子树 FindPath(root.right, target); list.remove(list.size()-1); // 移除最后一个结点(叶子结点) return all ; }
你可能感兴趣的文章
《LoadRunner性能测试实战》内容简介
查看>>
性能测试调整基础
查看>>
《LoadRunner性能测试实战》前言
查看>>
闲论LoadRunner的协议选择、Winsocket、C/S应用程序
查看>>
关XP把TCP并发链接数限制为10个后对LoadRunner性能测试的影响
查看>>
如何使用web_reg_save_param方法保存的多个参数?
查看>>
淡化优势的成功哲学
查看>>
《LoadRunner性能测试实战》即将出版
查看>>
中国历史上的十大黄金时代
查看>>
做事的态度与工作态度 (转自朱少民老师Blog)
查看>>
光芒国际传媒招聘测试开发工程师
查看>>
朋友公司招聘赴微软Tester,请推荐。。。
查看>>
八种消除沟通上的不良习惯地的方法
查看>>
《Web性能测试实战》性能测试用例模板
查看>>
《Web性能测试实战》性能测试报告模板
查看>>
《Web性能测试实战》性能测试计划模板
查看>>
《LoadRunner性能测试实战》第五章开头部分
查看>>
测试人员的开发水平要达到什么层次?
查看>>
项目中的软件质量管理
查看>>
功能测试用例设计
查看>>