算法leetcode每日一练层数最深叶子节点的和

Posted 二当家的白帽子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法leetcode每日一练层数最深叶子节点的和相关的知识,希望对你有一定的参考价值。


文章目录


2235. 两整数相加:

给你一棵二叉树的根节点 root ,请你返回 层数最深的叶子节点的和

样例 1:

输入:
	root = [1,2,3,4,5,null,6,7,null,null,null,null,8]
	
输出:
	15

样例 2:

输入:
	root = [6,7,8,2,7,1,3,9,null,1,4,null,null,null,5]
	
输出:
	19

提示:

  • 树中节点数目在范围 [1, 1 0 4 10^4 104] 之间。
  • 1 <= Node.val <= 100

分析

  • 面对这道算法题目,二当家陷入了沉思。
  • 最直观的方式就是先遍历一次计算树中的最深层数,然后再遍历统计节点和,但是这样需要遍历两次,有没有办法仅遍历一次呢?

题解

java

/**
 * Definition for a binary tree node.
 * public class TreeNode 
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() 
 *     TreeNode(int val)  this.val = val; 
 *     TreeNode(int val, TreeNode left, TreeNode right) 
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     
 * 
 */
class Solution 
    private int maxDep = 0;
	private int ans = 0;

	public int deepestLeavesSum(TreeNode root) 
		dfs(root, 1);
		return ans;
	

	private void dfs(TreeNode root, int dep) 
		if (root == null) 
			return;
		
		if (dep > maxDep) 
			maxDep = dep;
			ans = root.val;
		 else if (dep == maxDep) 
			ans += root.val;
		
		dfs(root.left, dep + 1);
		dfs(root.right, dep + 1);
	


c

/**
 * Definition for a binary tree node.
 * struct TreeNode 
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * ;
 */

void dfs(struct TreeNode* root, int dep, int* maxDep, int* ans) 
    if (!root) 
        return;
    
    if (dep > *maxDep) 
        *maxDep = dep;
        *ans = root->val;
     else if (dep == *maxDep) 
        *ans += root->val;
    
    dfs(root->left, dep + 1, maxDep, ans);
    dfs(root->right, dep + 1, maxDep, ans);


int deepestLeavesSum(struct TreeNode* root)
    int maxDep = 0;
    int ans = 0;
    dfs(root, 1, &maxDep, &ans);
    return ans;


c++

/**
 * Definition for a binary tree node.
 * struct TreeNode 
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) 
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) 
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) 
 * ;
 */
class Solution 
private:
    int maxDep = 0;
    int ans = 0;

    void dfs(TreeNode* root, int dep) 
        if (!root) 
            return;
        
        if (dep > maxDep) 
            maxDep = dep;
            ans = root->val;
         else if (dep == maxDep) 
            ans += root->val;
        
        dfs(root->left, dep + 1);
        dfs(root->right, dep + 1);
    
public:
    int deepestLeavesSum(TreeNode* root) 
        dfs(root, 1);
        return ans;
    
;

python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.ans = 0
        self.max_dep = 0

    def deepestLeavesSum(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode], dep: int) -> None:
            if not node:
                return
            if dep > self.max_dep:
                self.max_dep = dep
                self.ans = node.val
            elif dep == self.max_dep:
                self.ans += node.val
            dfs(node.left, dep + 1)
            dfs(node.right, dep + 1)

        dfs(root, 1)
        return self.ans
        

go

/**
 * Definition for a binary tree node.
 * type TreeNode struct 
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * 
 */
func deepestLeavesSum(root *TreeNode) int 
    ans := 0
	maxDep := 0

	var dfs func(node *TreeNode, dep int)
	dfs = func(node *TreeNode, dep int) 
		if node == nil 
			return
		
		if dep > maxDep 
			maxDep = dep
			ans = node.Val
		 else if dep == maxDep 
			ans += node.Val
		
		dfs(node.Left, dep+1)
		dfs(node.Right, dep+1)
	

	dfs(root, 1)
	return ans


rust

// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode 
//   pub val: i32,
//   pub left: Option<Rc<RefCell<TreeNode>>>,
//   pub right: Option<Rc<RefCell<TreeNode>>>,
// 
//
// impl TreeNode 
//   #[inline]
//   pub fn new(val: i32) -> Self 
//     TreeNode 
//       val,
//       left: None,
//       right: None
//     
//   
// 
use std::rc::Rc;
use std::cell::RefCell;
impl Solution 
    pub fn deepest_leaves_sum(root: Option<Rc<RefCell<TreeNode>>>) -> i32 
        fn dfs(node: Option<Rc<RefCell<TreeNode>>>, dep: i32, maxDep: &mut i32, ans: &mut i32) 
            if let Some(node) = node 
                if dep > *maxDep 
                    *maxDep = dep;
                    *ans = node.borrow().val;
                 else if dep == *maxDep 
                    *ans += node.borrow().val;
                
                dfs(node.borrow().left.clone(), dep + 1, maxDep, ans);
                dfs(node.borrow().right.clone(), dep + 1, maxDep, ans);
            
        

        let mut ans = 0;
        let mut maxDep = 0;
        dfs(root, 1, &mut maxDep, &mut ans);
        ans
    


typescript

/**
 * Definition for a binary tree node.
 * class TreeNode 
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) 
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     
 * 
 */

function deepestLeavesSum(root: TreeNode | null): number 
    let ans = 0;
    let maxDep = 0;

    function dfs(node: TreeNode | null, dep: number): void 
        if (!node) 
			return
		
		if (dep > maxDep) 
			maxDep = dep;
			ans = node.val;
		 else if(dep == maxDep) 
			ans += node.val;
		
		dfs(node.left, dep+1);
		dfs(node.right, dep+1);
    

    dfs(root, 1);
    return ans;
;


原题传送门:https://leetcode-cn.com/problems/deepest-leaves-sum/


非常感谢你阅读本文~
欢迎【👍点赞】【⭐收藏】【📝评论】~
放弃不难,但坚持一定很酷~
希望我们大家都能每天进步一点点~
本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


以上是关于算法leetcode每日一练层数最深叶子节点的和的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 1302. 层数最深叶子节点的和

1302. 层数最深叶子节点的和

LeetCode 1302. 层数最深叶子节点的和

LeetCode 641. 设计循环双端队列 / 1656. 设计有序流 / 302. 层数最深叶子节点的和

LeetCode 641. 设计循环双端队列 / 1656. 设计有序流 / 302. 层数最深叶子节点的和

1302-层数最深叶子节点的和