剑指 Offer 34. 二叉树中和为某一值的路径

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

首先需要注意的是:根结点出发->叶子节点才算是一条完整的路径

非递归-stack+先序遍历

先序遍历可以先一头压到低,再慢慢返回拿到结果

class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> tmp_res;
        stack<TreeNode*> node_stack;

        if(!root) return res;

        while(root || !node_stack.empty()){
            while(root){
                node_stack.push(root);
                tmp_res.push_back(root->val);
                sum -= root->val;
                root = root->left?root->left:root->right;//避免一开始就没有左子树的情况
            }

            root = node_stack.top();
            if(sum==0 && !root->left && !root->right)
                res.push_back(tmp_res);

            tmp_res.pop_back();
            sum += root->val;
            node_stack.pop();

            //遍历右子树
            if(!node_stack.empty() && node_stack.top()->left==root)
                root = node_stack.top()->right;
            else
                root = nullptr;

        }

        return res;
    }
};



递归

猜你喜欢

转载自www.cnblogs.com/zhouyc/p/13204977.html