二叉树路径问题

来源:互联网 发布:金融产品设计书籍知乎 编辑:程序博客网 时间:2024/04/30 00:12

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

//递归版本/*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> > Path;        vector<int> temp;        if(root!=NULL)            Find(root,expectNumber,0,Path,temp);        return Path;    }    void Find(TreeNode* root,int n,int sum,vector<vector<int> > &Path,vector<int> &temp){        temp.push_back(root->val);        sum+=root->val;        if(root->left==NULL&&root->right==NULL&&sum==n){            Path.push_back(temp);        }else{            if(root->left)                Find(root->left,n,sum,Path,temp);            if(root->right)                Find(root->right,n,sum,Path,temp);        }        temp.pop_back();    }};
//非递归版本//思路:1.按先序遍历把当前节点cur的左孩子依次入栈同时保存当前节点,每次更新当前路径的和sum;2.判断当前节点是否是叶子节点以及sum是否等于expectNumber,如果是,把当前路径放入结果中。3.遇到叶子节点cur更新为NULL,此时看栈顶元素,如果栈顶元素的把栈顶元素保存在last变量中,同时弹出栈顶元素,当期路径中栈顶元素弹出,sum减掉栈顶元素,这一步骤不更改cur的值;4.如果步骤3中的栈顶元素的右孩子存在且右孩子之前没有遍历过,当前节点cur更新为栈顶的右孩子,此时改变cur=NULL的情况。#include <iostream>#include <vector>using namespace std;struct TreeNode{    int val;    TreeNode *left;    TreeNode *right;    TreeNode(int x) : val(x), left(NULL), right(NULL){}}vector<vector<int> > FindPath(TreeNode *root, int expectNumber){    vector<vector<int> > res;       if (root == NULL)        return res;    stack<TreeNode *> s;    s.push(root);    int sum = 0; //当前和    vector<int> curPath; //当前路径    TreeNode *cur = root; //当前节点    TreeNode *last = NULL; //保存上一个节点    while (!s.empty()){        if (cur == NULL){            TreeNode *temp = s.top();            if (temp->right != NULL && temp->right != last){                cur = temp->right; //转向未遍历过的右子树            }else{                last = temp; //保存上一个已遍历的节点                s.pop();                curPath.pop_back(); //从当前路径删除                sum -= temp->val;            }  }        else{            s.push(cur);            sum += cur->val;            curPath.push_back(cur->val);            if (cur->left == NULL && cur->right == NULL && sum == expectNum){                res.push_back(curPath);            }            cur = cur->left; //先序遍历,左子树先于右子树        }    }    return res;}
0 0
原创粉丝点击