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;
    }
    
  • 相关阅读:
    HDU ACM 1020 Encoding
    HDU ACM 1019 Least Common Multiple
    HDU ACM 1009 FatMouse' Trade
    HDU ACM 1032 The 3n + 1 problem
    HD ACM 1061 Rightmost Digit
    UVa 401 Palindromes
    UVa 489 Hangman Judge
    HDU ACM 1071 The area
    5/25
    受涼6/8
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13394057.html
Copyright © 2011-2022 走看看