zoukankan      html  css  js  c++  java
  • 【剑指Offer-举例让抽象问题具体化】面试题34:二叉树中和为某一值的路径

    题目描述

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

    思路

    使用dfs和回溯。当遍历到某一结点时,记录当前路径的长度:如果当前长度小于期待长度,将当前结点加入路径中继续遍历;如果当前长度大于期待长度,则该路径已不可能;如果当前长度等于期待长度且当前结点是叶子结点,则找到一条路径。代码如下:

    /*
    struct TreeNode {
    	int val;
    	struct TreeNode *left;
    	struct TreeNode *right;
    	TreeNode(int x) :
    			val(x), left(NULL), right(NULL) {
    	}
    };*/
    class Solution {
    public:
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<int> path;
            vector<vector<int>> ans;
            int curLen = 0;    //当前路径长度
            FindPathCore(root, expectNumber, curLen, path, ans);
            
            return ans;
        }
        
        void FindPathCore(TreeNode* root, int expectNum, int curLen, vector<int> path, vector<vector<int>>& ans){
            if(root==nullptr)
                return;
            curLen+=root->val;
            if(curLen>expectNum)    //当前值大于期待值,该路径已不可能
                return;
            if(curLen<expectNum)    //当前值小于期待值,将当前结点加入路径
                path.push_back(root->val);
            if(curLen==expectNum){    //当前值等于期待值
                if(root->left==nullptr && root->right==nullptr){  //当为叶子节点时才是正确的路径
                    path.push_back(root->val);
                    ans.push_back(path);
                }
                else path.push_back(root->val);
            }
            
            FindPathCore(root->left, expectNum, curLen, path, ans);
            FindPathCore(root->right, expectNum, curLen, path, ans);
        }
    };
    
  • 相关阅读:
    【我也不知道是从哪儿来的题】—树(矩阵树定理)
    【我也不知道是从哪儿来的题】—树(矩阵树定理)
    【BJOI2019 Day2】简要题解
    【BJOI2019 Day2】简要题解
    【BJOI2019 Day1】简要题解
    【BJOI2019 Day1】简要题解
    【BZOJ3935】—RBTree(树形dp)
    【BZOJ3935】—RBTree(树形dp)
    2016-8-12
    深入理解web项目的配置文件
  • 原文地址:https://www.cnblogs.com/flix/p/12468028.html
Copyright © 2011-2022 走看看