zoukankan      html  css  js  c++  java
  • 二叉树中和为某个值得路径

    题目描述

    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
    实现:
    class Solution {
            vector<int> in ;
            vector<vector<int>> out ;
    public:
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            if(!root)
                return out;
            in.push_back(root->val);
            if(root->left == 0 && root->right == 0 && root->val == expectNumber)
            {
                out.push_back(in);
            }    
            if(root->left)
            {
                FindPath(root->left,expectNumber - root->val);
                if(!in.empty())
                    in.pop_back();
             }   
            if(root->right)
            {
                FindPath(root->right,expectNumber - root->val);
                if(!in.empty())
                    in.pop_back();
            }
            return out;
         }
    };

    样例做法:

    class Solution {
            vector<int> in ;
            vector<vector<int>> out ;
    public:
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            if(!root)
                return out;
            in.push_back(root->val);
            if(root->left == 0 && root->right == 0 && root->val == expectNumber)
            {
                out.push_back(in);
            }    
            if(root->left)
            {
                FindPath(root->left,expectNumber - root->val);
             }   
            if(root->right)
            {
                FindPath(root->right,expectNumber - root->val);
            }
            if(!in.empty())
                in.pop_back();
            return out;
         }
    };

    本来还以为样例不对,

        3

      5    8

    2  6  7  9

    本来认为5为根时遍历完左右没有弹出5,后来终于想通,忘记了以5为根时后面还会走if弹出。

  • 相关阅读:
    poj 2676 Suduku (dfs)
    poj 1562 Oil Deposits (dfs)
    poj 2907 Collecting Beepers (dfs)
    poj 1655 Balancing Act (树形dfs)
    poj 3411 Paid Roads (dfs)
    hdu 2896 病毒侵袭 (AC)
    hdu 3065 病毒侵袭持续中 (AC)
    poj 2251 Dungeon Master (bfs)
    java中debug使用
    Swing入门级小项目总结
  • 原文地址:https://www.cnblogs.com/Lune-Qiu/p/8729296.html
Copyright © 2011-2022 走看看