zoukankan      html  css  js  c++  java
  • 面试题34:二叉树中和为某一值的路径

    考察二叉树的前序遍历。

    C++版本

    #include <iostream>
    #include <vector>
    #include <stack>
    #include <cstring>
    #include <string>
    #include <queue>
    #include <algorithm>
    #include "TreeNode.h"
    using namespace std;
    
    // vector<int>& path传递的是引用,会修改实参的值;也可以传递指针vector<int>* path
    void FindPath(TreeNode* root, int expectedSum, vector<int>& path, int currentSum, vector<vector<int>>& ans){
        currentSum= currentSum + root->val;
        path.push_back(root->val);
    
        // 如果是叶子节点,并且路径上节点值的和等于输入的值,则添加这条路径
        bool isLeaf = root->left == nullptr && root->right == nullptr;
        if(isLeaf && currentSum == expectedSum){
    
            // 添加一行路径
            ans.push_back(vector<int>());
            cout<<"A path is found:";
            for(int i = 0; i < path.size(); i++){
                cout<<path[i]<<"	";
                ans[ans.size() - 1].push_back(path[i]);
            }
            cout<<endl;
        }
    
        // 如果不是叶节点,则遍历它的子节点
        if(root->left != nullptr)
            FindPath(root->left, expectedSum, path, currentSum, ans);
        if(root->right != nullptr)
            FindPath(root->right, expectedSum, path, currentSum, ans);
    
        path.pop_back();
    }
    
    vector<vector<int>> FindPath(TreeNode* root,int expectNumber) {
        vector<vector<int>> ans;
        if(root == nullptr)
            return ans;
        vector<int> path;
        int currentSum = 0;
        FindPath(root, expectNumber, path, currentSum, ans);
        return ans;
    }
    
    int main()
    {
    
        return 0;
    }
    
  • 相关阅读:
    Java.io.outputstream.PrintStream:打印流
    Codeforces 732F. Tourist Reform (Tarjan缩点)
    退役了
    POJ 3281 Dining (最大流)
    Light oj 1233
    Light oj 1125
    HDU 5521 Meeting (最短路)
    Light oj 1095
    Light oj 1044
    HDU 3549 Flow Problem (dinic模版 && isap模版)
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13394057.html
Copyright © 2011-2022 走看看