目录
二叉树路径总和
访问量:1431

一、简介

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

说明: 叶子节点是指没有子节点的节点。

示例: 

给定如下二叉树,以及目标和 sum = 22

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

二、代码实现

1、递归版本

type Queue struct {
	data []*TreeNode
}

func (q *Queue) Push(n *TreeNode) {
	if q.data == nil {
		q.data = make([]*TreeNode, 0)
	}

	q.data = append(q.data, n)
}

func (q *Queue) Pop() *TreeNode {
	if len(q.data) == 0 {
		return nil
	}

	node := q.data[0]
	q.data = q.data[1:]

	return node
}

func (q *Queue) Len() int {
	return len(q.data)
}

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func hasPathSum(root *TreeNode, sum int) bool {
    if root == nil {
        return false
    }
    
    if root.Left == nil && root.Right == nil {
        return root.Val == sum
    } 
    
    if root.Left != nil {
        isOk := hasPathSum(root.Left, sum - root.Val)
        
        if isOk {
            return true
        }
    }
    
    if root.Right != nil {
        isOk := hasPathSum(root.Right, sum - root.Val)
        
        if isOk {
            return true
        }
    }
    
    return false
}