码迷,mamicode.com
首页 > 其他好文 > 详细

376 二叉树的路径和

时间:2018-06-19 14:44:39      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:tmp   面试   wrapper   遇到   数据   desc   ram   core dump   提交   

原题网址:https://www.lintcode.com/problem/binary-tree-path-sum/description

描述

给定一个二叉树,找出所有路径中各节点相加总和等于给定 目标值 的路径。

一个有效的路径,指的是从根节点到叶节点的路径。

您在真实的面试中是否遇到过这个题?  

样例

给定一个二叉树,和 目标值 = 5:

     1
    /    2   4
  /  2   3

返回:

[
  [1, 2, 2],
  [1, 4]
]

标签
二叉树遍历
二叉树
 
思路:二叉树遍历节点,递归。
可定义一个函数,递归遍历所有路径(类似于前序遍历,根左右的顺序)。遍历每条路径时遇到叶子结点就判断sum是否为target,是将路径节点值数组压入结果中,继续遍历其他路径;不是,依旧继续遍历其他路径。注意遍历其他路径之前应消除当前步骤的影响,即sum减去当前值,路径节点数组pop掉当前节点值。
 
AC代码:
/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param root: the root of binary tree
     * @param target: An integer
     * @return: all valid paths
     */
    vector<vector<int>> binaryTreePathSum(TreeNode * root, int target) {
        // write your code here
    vector<vector<int>> result;
    if (root==NULL)
    {
        return result;
    }
    vector<int> tmp;
    int sum=0;
    trav(result,tmp,root,target,sum);
    return result;
    }
    
    void trav(vector<vector<int>> &result,vector<int> &tmp, TreeNode * root, int target, int & sum)
{
    tmp.push_back(root->val);
    sum+=root->val;

    if (root->left==NULL&&root->right==NULL)
    {
        if (sum==target)
        {
            result.push_back(tmp);
        }
        return ;
    }
    if (root->left!=NULL)
    {
        trav(result,tmp,root->left,target,sum);
        sum=sum-root->left->val;
        tmp.pop_back();
    }
    if (root->right!=NULL)
    {
        trav(result,tmp,root->right,target,sum);
        sum=sum-root->right->val;
        tmp.pop_back();
    }
}
};

 

最开始提交的代码在递归语句之前没有判断root->left、root->right是否为NULL导致只通过27%的数据,提示错误 segmentation fault (core dumped)。想了下应该是如果有左右孩子其中一个为空的话,递归时取val值出错。

376 二叉树的路径和

标签:tmp   面试   wrapper   遇到   数据   desc   ram   core dump   提交   

原文地址:https://www.cnblogs.com/Tang-tangt/p/9198391.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!