Last Commit: 2024-01-06 17:50:27

views:

Table of Content

112. Path Sum

source: https://leetcode.com/problems/path-sum/

Question

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

思路

主要还是带着参数去traverse二叉树,属于比较常规的基础题。

pub fn has_path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> bool {
  fn dfs(node: Option<Rc<RefCell<TreeNode<i32>>>>, sum: i32, target: i32) -> bool {
    if let Some(node) = node {
      let mut node = node.borrow_mut();
      if node.left.is_none() && node.right.is_none() && sum + node.val == target || dfs(node.left.take(), sum + node.val, target) || dfs(node.right.take(), sum + node.val, target) {
        return true;
      }
    }
    false
  }
  dfs(root, 0, target_sum)
}

End

掌握好traverse基础,这题就很easy。