leetcode Path Sum
来源:互联网 发布:自行车运动软件 编辑:程序博客网 时间:2024/06/14 01:38
https://oj.leetcode.com/problems/path-sum/
实际上可看做二叉树的遍历。
只不过要比二叉树的遍历多存储一个变量,就是根节点到当前节点的和。
可以深度遍历也可广度遍历
深度遍历(前序遍历)
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root==null)return false; Stack<TreeNode>stack=new Stack<TreeNode>(); Stack<Integer>number=new Stack<Integer>(); stack.push(root); number.push(root.val); while(!stack.isEmpty()){ TreeNode temp=stack.pop(); int current=number.pop(); if(temp.right==null&&temp.left==null){ if(current==sum)return true; } if(temp.right!=null){ stack.push(temp.right); number.push(temp.right.val+current); } if(temp.left!=null){ stack.push(temp.left); number.push(temp.left.val+current); } }//while return false; }}广度遍历(层次遍历)
在java中LIinkedList可做queue使用
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root==null)return false; LinkedList<TreeNode>list=new LinkedList<TreeNode>(); LinkedList<Integer>number=new LinkedList<Integer>(); list.offer(root); number.offer(root.val); int ret=0; while(!list.isEmpty()){ TreeNode temp=list.poll(); int cur=number.poll(); if(temp.left==null&&temp.right==null){ if(cur==sum)return true; } if(temp.left!=null){ list.offer(temp.left); number.offer(temp.left.val+cur); } if(temp.right!=null){ list.offer(temp.right); number.offer(temp.right.val+cur); } } return false; }}
下面是一个递归算法
public class Solution { public boolean hasPathSum(TreeNode root, int sum) { if(root==null)return false; sum-=root.val; if(root.left==null&&root.right==null)return sum==0; return hasPathSum(root.left,sum)||hasPathSum(root.right,sum); }}
0 0
- leetcode Path Sum && Path Sum ||
- 【Leetcode】Path Sum (Sum)
- leetcode:leetcode :Path Sum
- 【Leetcode】Path Sum II (Sum)
- LeetCode: Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- LeetCode Minimum Path Sum
- LeetCode Path Sum
- LeetCode Path Sum II
- [Leetcode] Path Sum
- [Leetcode] Path Sum II
- LeetCode : Minimum Path Sum
- [Leetcode] Minimum Path Sum
- LeetCode: Path Sum
- LeetCode: Path Sum II
- [LeetCode] Path Sum
- [LeetCode] Path Sum II
- Makefile 中:= ?= += =的区别
- PCA and SVD
- Mac中配置java环境
- 算法分析(1)-循环的时间复杂度
- 源代码加密软件
- leetcode Path Sum
- 运算符重载之->为下标成员运算符,而不是指针
- Matlab资料汇总暨MATLAB中文论坛帖子整理(二)
- OpenCV Error: Assertion failed (size.width>0 && size.height>0) in cv::imshow
- ubuntu terminal theme with
- 算法训练 操作格子
- HDU 1873 看病要排队
- 【华为OJ】计算字符串最后一个单词的长度
- 虚拟机VMware与主机共享文件介绍