zoukankan      html  css  js  c++  java
  • 24、剑指offer--二叉树中和为某一值的路径

    题目描述
    输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
     
    解题思路:本题采用先序遍历,遍历到叶子节点,如果和不等于其值,则返回至上一层的根结点,本题使用栈结构来存储路径,这样可以方便返回上一父结点的时候,将当前结点从路径中删除
     1 /*struct TreeNode {
     2     int val;
     3     struct TreeNode *left;
     4     struct TreeNode *right;
     5     TreeNode(int x) :
     6             val(x), left(NULL), right(NULL) {
     7     }
     8 };*/
     9 class Solution {
    10 public:
    11     vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
    12         vector<int> tmp;
    13         vector<vector<int> >result;
    14         if(root == NULL || expectNumber<=0)
    15             return result;
    16         IsPath(root,expectNumber,result,tmp);
    17         return result;
    18     }
    19     void IsPath(TreeNode* root,int expectNumber,vector<vector<int> > &findPath,vector<int> &path)//不是取地址的话,结果不正确
    20     {
    21         path.push_back(root->val);
    22         if(root == NULL)
    23             return;
    24         bool isLeaf = (root->left == NULL)&&(root->right == NULL);
    25         if((root->val == expectNumber)&&isLeaf)
    26         {
    27             findPath.push_back(path);
    28         }
    29         else
    30         {
    31             if(root->left != NULL) IsPath(root->left,expectNumber-root->val,findPath,path);
    32             if(root->right != NULL) IsPath(root->right,expectNumber-root->val,findPath,path);
    33         }
    34         path.pop_back();
    35     }
    36 };
    备注:vector<vector<int> > r接收返回值,其输出应该为
     1 vector<vector<int> > r;
     2 r = s.FindPath(T1,n);
     3      
     4 for(int i=0;i<r.size();i++)
     5 {
     6     for(int j=0;j<r[i].size();j++)
     7     {
     8         cout<<r[i][j]<<" ";
     9     }
    10     cout<<endl;
    11 }
  • 相关阅读:
    Thinking in Java
    Interview Common Sample Codes
    Longest Common Substring
    Mac键盘按键符号
    ElasticSearch
    Variables and Arithmetic Expression
    Associative Containers
    Container Adaptors
    string Type
    初识 tk.mybatis.mapper 通用mapper
  • 原文地址:https://www.cnblogs.com/qqky/p/6910597.html
Copyright © 2011-2022 走看看