打印二叉树的路径

题目描述:

输入一颗二叉树的跟节点和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。(注意: 在返回值的list中,数组长度大的数组靠前)。

优秀代码:

class Solution {
public:
    vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> result;
        vector<int> vec;
        if(root){
            FindCore(root, expectNumber, result, vec);
        }
        return result;
    }
    
    void FindCore(TreeNode* root, int t, vector<vector<int>> &vec, vector<int> &trace){
        trace.push_back(root->val);
        if(!root->left && !root->right){
            if(t == root->val){
                vec.push_back(trace);
            }
        }
        if(root->left){
            FindCore(root->left, t - root->val, vec, trace);
        }
        if(root->right){
            FindCore(root->right, t-root->val, vec, trace);
        }
        trace.pop_back();
  }
};

  每次递归的时候,先将该节点放入堆栈中,用target减去当前结点的值,当遍历到最后一个节点的时候如果target的值不等于最后一个节点的值,那么就pop_back(),将该节点弹出来。

posted @ 2019-03-21 20:26  Howardwang  阅读(430)  评论(0编辑  收藏  举报