Leetcode-437. Path Sum III

来源:互联网 发布:centos添加yum源 编辑:程序博客网 时间:2024/05/21 08:58

Description:

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8      10     /  \    5   -3   / \    \  3   2   11 / \   \3  -2   1Return 3. The paths that sum to 8 are:1.  5 -> 32.  5 -> 2 -> 13. -3 -> 11
解题思路:
设置一个全局变量count,以每个结点为根结点,遍历以它为根的子树的所有的路径,每次访问到一个新节点计算到根结点的结点之和,判断是否等于
sum,相等的话count加一。采用递归的形式深度遍历。
Solution:
class Solution {public:    int pathSum(TreeNode* root, int sum) {        if(!root)  return 0;        int count = 0;//保存符合的路径总数        stack<TreeNode*> st;        TreeNode* temp;        st.push(root);        while(!st.empty())          //遍历每一个结点        {            int total = 0;            temp = st.top();            DFS(temp, count, sum, total);  //以每个结点为根结点,搜索符合的路径            st.pop();            if(temp ->right) st.push(temp->right);            if(temp ->left ) st.push(temp->left );        }        return count;    }    void DFS(TreeNode* root, int& count, int sum, int& total)    {        if(!root)  return;        total += root->val;     //保存以root为根节点的到当前访问的结点的路径上值的和        if(total == sum)    count++;        if(root->left)        {            DFS(root->left, count, sum, total);            total -= root->left->val;   //左子树访问结束,total值要恢复到root结点的值        }        if(root->right)        {            DFS(root->right, count, sum, total);            total -= root ->right->val;  //同样,恢复total值        }            }};
原创粉丝点击