zoukankan      html  css  js  c++  java
  • 12 二叉树中和为某一值的路径

    0 引言

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

    1 抽象问题具体化

    举例1:树的形态如图所示。给定的整数值为22,求路径。

    解答:所有的路径总共有三条,分别是

    1)10->5->4,和为19;

    2)10->5->7,和为22,打印出路径信息;

    3)10->12,和为22,打印出路径信息.

    2 具体问题抽象分析

    1)currentSum 求解,每次访问即运行 currentSum += root->val;

    2)thisPath.push_back(root->val);

    3)对当前结点进行判断,如果当前结点为叶节点且满足 currentSum == expectedNum, 则myPaths.push_back(thisPath);

    4)访问当前结点的左结点,访问当前结点的右结点;

    5)访问完毕退回,thisPath.pop_back();

    6) 根据路径长短对所有路径进行排序,返回结果.

    3 demo 

        void visitPath(vector<vector<int>> &myPaths, vector<int> &thisPath, TreeNode* root, int expectNumber, int currentSum){
            currentSum += root->val;
            thisPath.push_back(root->val);
            if(currentSum == expectNumber && root->left == NULL && root->right == NULL)
                myPaths.push_back(thisPath);
            if(root ->left != NULL)
                visitPath(myPaths, thisPath, root->left, expectNumber, currentSum);
            if(root ->right != NULL)
                visitPath(myPaths, thisPath, root->right, expectNumber, currentSum);
            // 访问完退回去
            thisPath.pop_back();
            currentSum -= root->val;
        }
        vector<vector<int> > FindPath(TreeNode* root,int expectNumber) {
            vector<vector<int>> myPaths;
            if(root == NULL)
                return myPaths;
            vector<int> thisPath;
            int currentSum = 0;
            visitPath(myPaths, thisPath, root, expectNumber, currentSum);
            // 排序
            for(int i=1;i<myPaths.size();i++){
                for(int j=i;j>0;j--){
                    if(myPaths[j].size() > myPaths[j-1].size())
                        myPaths[j].swap(myPaths[j-1]);
                }
            }
            return myPaths;        
        }

    4 代码优化

  • 相关阅读:
    D
    NOI 1.7编程基础之字符串(35题)
    HYSBZ 2145 悄悄话
    POJ 2406 Power Strings
    POJ 3461 Oulipo[附KMP算法详细流程讲解]
    POJ 3974 Palindrome
    POJ 1002 487-3279
    POJ 1182 食物链
    POJ 2524 Ubiquitous Religions
    HDU 1251 统计难题
  • 原文地址:https://www.cnblogs.com/ghjnwk/p/10049982.html
Copyright © 2011-2022 走看看