[C++]LeetCode: 90 Path Sum

题目:

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

return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Answer 1: 递归法 DFS

思路:先判断此处是否存在节点,如果不存在,返回false。说明两种情况,第一种为空树,无论sum为何值,都返回false.(注意这个特殊情况,sum为0也返回false.题中设定)。第二种,都深度搜索到叶结点的下一个空节点,仍然未符合sum的条件,说明此条路径不可行,返回false.
接下来判断,如果当前节点是叶结点(左右结点为空),并且当前节点值和sum值(不断更新)相等,说明找到一条路径,可以返回true. 设置好递归终止条件后,判断完当前节点,开始递归搜索其左右子树。

Attention: 

1. 判断是否是叶子结点和值等于sum, 注意这个递归终止条件

/如果该结点是叶结点,并且它的值为sum 返回true 找到path
        if(!root->left && !root->right && root->val == sum) return true;

2. 如果为空数,sum为0,仍然返回false.

复杂度:树的遍历,时间复杂度是O(n),空间复杂度是O(logn)

AC Code:

/**
 * Definition for binary tree
 * 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) {
        if(root == NULL) return false;

        //如果该结点是叶结点,并且它的值为sum 返回true 找到path
        if(!root->left && !root->right && root->val == sum) return true;

        int newSum = sum - root->val;
        return hasPathSum(root->left, newSum) || hasPathSum(root->right, newSum);
    }
};

Answer 2: 非递归方法

思路:定义两个栈,一个保存前序遍历的结点,一个保存前序遍历的结点的累加值。维护一个当前节点node. 如果栈非空或者结点非空有一个成立,则继续前序遍历。如果节点不为NULL,则继续前序遍历,添加节点和更新val并添加进stval. 同时更新node为左孩子结点。如果节点为NULL, 则pop其父结点和父结点的累加值,如果父结点为叶子结点并且val == sum, 返回true,否则更新node为其父结点的右结点。如果右结点非空,则会继续pop其父结点的父结点,走另外一条路(即父结点的右兄弟结点)。

Attention:

1. 循环条件必须是栈非空或者node不为叶子结点,因为初始条件,栈为空,node还没添加到栈里。

while(!st.empty() || node != NULL)

2. 注意维护一个节点node, 用于指示前序遍历的当前节点,便于操作。

<span style="font-size:14px;">TreeNode* node = root;</span>

3. 掌握前序遍历的方法。维护一个stack, 先不断取左子树,知道叶子结点,之后退回,取右子树。

AC Code:

/**
 * Definition for binary tree
 * 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) {
        //定义两个栈,一个存放前序遍历的结点,一个存放前序遍历时的结点累加值;
        if(root == NULL) return false;
        stack<TreeNode*> st;
        stack<int> stval;
        TreeNode* node = root;
        int val = 0;

        while(!st.empty() || node != NULL)
        {
            //如果没有到达叶子结点,就一直递归往下
            if(node != NULL)
            {
                val += node->val;
                st.push(node);
                stval.push(val);
                node = node->left; //先遍历左子树
            }
            //如果到达了NULL结点,就判断其父结点是否是叶子结点,并且是否满足sum关系,如果不满足,遍历其父结点的右结点
            else
            {
                node = st.top();
                st.pop();
                val = stval.top();
                stval.pop();
                if(!node->left && !node->right && val == sum) return true;
                node = node->right; //如果这条路径不等于sum,遍历该结点的右子树。由于pop了st和stval,所以此时为根结点的值
            }
        }

        return false;
    }
};
时间: 2024-10-13 23:39:38

[C++]LeetCode: 90 Path Sum的相关文章

【Leetcode】Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] 思路:与[Leetcode]Path Sum 不同

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

1.题目名称 Path Sum(树的根节点到叶节点的数字之和) 2.题目地址 https://leetcode.com/problems/path-sum/ 3.题目内容 英文: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. 中文:给定一颗二叉树,如

LeetCode &quot;Minimum Path Sum&quot; - 2D DP

An intuitive 2D DP: dp[i][j] = min(grid[i-1][j-1] + dp[i-1][j], grid[i-1][j-1] + dp[i][j+1]) class Solution { public: int minPathSum(vector<vector<int> > &grid) { // dp[i][j] = min(dp[i-1][j] + dp[i][j], dp[i][j-1] + dp[i][j]); int n = gri

【LeetCode】Path Sum

题目 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 return true,

Leetcode:Minimum Path Sum 矩形网格最小路径和

Minimum Path Sum: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 解题分析: 每次只能向下或者向

[leetcode]Minimum Path Sum @ Python

原题地址:https://oj.leetcode.com/problems/minimum-path-sum/ 题意: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or r

leetcode -day17 Path Sum I II &amp; Flatten Binary Tree to Linked List &amp; Minimum Depth of Binary Tree

1.  Path Sum 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 r

[LeetCode] 437. Path Sum III_ Easy tag: DFS

You are given a binary tree in which each node contains an integer value. Find the number of paths that sum to a given value. The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to

[LeetCode][JavaScript]Path Sum II

Path Sum II Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / 4 8 / / 11 13 4 / \ / 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] https://leetco