Path Sum
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
题意:给定一个二进制树和求和,判断树有根到叶的路径,沿该路径的所有值加起来等于给定的总和。
解题思路:需要遍历二叉树,所以采用前序遍历思路来实现,前序遍历需要使用递归思路来实现,同时只有在叶子节点时才进行求和比较,而叶子节点的特点是leaf->left == NULL && leaf->right == NULL.
C语言实现代码如下:
/**
* 解题思路:采用前序遍历方法,从根节点开始遍历,当遍历到叶子节点时,进行值比较,相等返回1,不等返回0
* 前序遍历的方法主要利用递归来实现,
* 此代码:主要通过设备标志位来实现,若某个分支求和等于给定的值,则设标志位flag为1,并返回,否