图片.png

递归阶梯思路

  1. package main
  2. import "fmt"
  3. type TreeNode struct {
  4. Val int
  5. Left *TreeNode
  6. Right *TreeNode
  7. }
  8. //递归解决思路
  9. func hasPathSum(root *TreeNode, sum int) bool {
  10. if root == nil{
  11. return false
  12. }
  13. // 当前是叶子节点 判断当前是否是等于目标值
  14. if root.Left==nil&&root.Right==nil{
  15. return root.Val==sum
  16. }
  17. return hasPathSum(root.Left,sum-root.Val)||hasPathSum(root.Right,sum-root.Val)
  18. }
  19. //https://leetcode-cn.com/problems/path-sum/
  20. func main() {
  21. a := &TreeNode{
  22. Val: 5,
  23. }
  24. b := &TreeNode{
  25. Val: 4,
  26. }
  27. a.Left = b
  28. c := &TreeNode{
  29. Val: 8,
  30. }
  31. a.Right = c
  32. d := &TreeNode{
  33. Val: 11,
  34. }
  35. b.Left = d
  36. e := &TreeNode{
  37. Val: 7,
  38. }
  39. d.Left = e
  40. f := &TreeNode{
  41. Val: 2,
  42. }
  43. d.Right = f
  44. // 4,2,5,1,6,3
  45. fmt.Println(hasPathSum(a,21))
  46. fmt.Println(hasPathSum(a,22))
  47. }

图片.png

迭代方式

  1. func hasPathSum1(root *TreeNode, sum int) bool {
  2. if root == nil{
  3. return false
  4. }
  5. stack := make([]*TreeNode,0)
  6. vals := make([]int,0)
  7. stack = append(stack,root)
  8. vals = append(vals,sum)
  9. for len(stack)>0{
  10. curr :=stack[len(stack)-1]
  11. stack = stack[:len(stack)-1]//出栈
  12. val :=vals[len(vals)-1]
  13. vals = vals[:len(vals)-1] // 出栈
  14. if curr.Left==nil&&curr.Right==nil&&val ==curr.Val {// 如果当前节点已经为叶子节点并且节点上的数字等于当前和s,则返回true
  15. return true
  16. }
  17. if curr.Left!=nil {
  18. stack = append(stack,curr.Left)
  19. vals = append(vals,val-curr.Val)
  20. }
  21. if curr.Right!=nil {
  22. stack = append(stack,curr.Right)
  23. vals = append(vals,val-curr.Val)
  24. }
  25. }
  26. return false
  27. }

java

  1. class Solution {
  2. public boolean hasPathSum(TreeNode root, int sum) {
  3. if (root == null)
  4. return false;
  5. Stack<Pair<TreeNode, Integer>> stack = new Stack<Pair<TreeNode, Integer>>();
  6. stack.push(new Pair<TreeNode, Integer>(root, sum - root.val));
  7. while ( !stack.isEmpty() ) {
  8. Pair<TreeNode, Integer> top = stack.pop();
  9. TreeNode node = top.getKey();
  10. int curr_sum = top.getValue();
  11. if ((node.right == null) && (node.left == null) && (curr_sum == 0))
  12. return true;
  13. if (node.right != null) {
  14. stack.push(new Pair<TreeNode, Integer>(node.right, curr_sum - node.right.val));
  15. }
  16. if (node.left != null) {
  17. stack.push(new Pair<TreeNode, Integer>(node.left, curr_sum - node.left.val));
  18. }
  19. }
  20. return false;
  21. }
  22. }