zoukankan      html  css  js  c++  java
  • 112. Path Sum (Tree; DFS)

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

    For example:
    Given the below binary tree and sum = 22,

                  5
                 / 
                4   8
               /   / 
              11  13  4
             /        
            7    2      1
    
    struct TreeNode {
        int val;
        TreeNode *left;
        TreeNode *right;
        TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    };
    class Solution {
    public:
        bool hasPathSum(TreeNode *root, int sum) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            if(!root) return false;
            flag = false;
            target = sum;
            preOrder(root,0);
            return flag;
            
        }
        void preOrder(TreeNode* node,int sum){
            sum = node->val + sum; //递归前,加上当前节点
            if(node->left)
            {           
                preOrder(node->left,sum);
            }
            if(node->right)
            {           
                preOrder(node->right,sum);
            }
            if(!node->left && !node->right && sum == target) //递归结束条件:到了叶子节点
            {
                flag = true;
            }
        }
    private:
        bool flag;
        int target;
    };
  • 相关阅读:
    模块
    匿名函数
    推导式
    函数 重点
    新的
    知识点补充
    unity学习规划与进度
    暂停·笔记
    解决问题__max 模型白色 材质球换没用
    Max__cs骨骼
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4854200.html
Copyright © 2011-2022 走看看