面试题25_二叉树中和为某一值的路径

来源:互联网 发布:淘宝质量问题退货运费 编辑:程序博客网 时间:2024/06/04 19:52

题目描述


输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。


解题思路

当用先序遍历的方式访问某一结点时候,我们把该结点加入到当前路径,并计算累加和。

若累加和刚好等于输入的整数,并且该节点为叶子节点,那么当前路径符合要求。

如果当前节点不是叶子节点,那么继续访问它的子节点。

当前节点访问结束后,递归地返回到它的父节点。

注意:在退出当前路径的时候,要在当前路径中删除当前节点,以确保返回父节点时,路径刚好是从根节点到父节点的路径。累加和也要减去当前节点的值。


实现代码

/*struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}};*/class Solution {public:    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {                vector<vector<int>> ansPath;        vector<int> curPath;        if(root == nullptr)            return ansPath;        int curNum = 0;                findAPath(root,ansPath,curPath,expectNumber,curNum);                return ansPath;    }    //注意用引用传递参数    void findAPath(TreeNode* root,vector<vector<int> > &ansPath,vector<int> &curPath, int expNum, int curNum)    {        curNum += root->val;//累加                curPath.push_back(root->val);//把当前节点入栈                bool isLeaf = (root->left == nullptr) && (root->right == nullptr);                if(isLeaf && curNum == expNum)        {        ansPath.push_back(curPath);//找到就压栈        }                if(root->left != nullptr)            findAPath(root->left, ansPath, curPath, expNum, curNum);                if(root->right != nullptr)            findAPath(root->right, ansPath, curPath, expNum, curNum);                curNum -= root->val;//回到上一个节点 要减去当前节点的值        curPath.pop_back();//在返回到父节点之前,要删除当前节点    }};


1 0
原创粉丝点击