算法leetcode|剑指 Offer 55 - I. 二叉树的深度|104. 二叉树的最大深度(rust和go)

发布于:2022-12-10 ⋅ 阅读:(287) ⋅ 点赞:(0)


剑指 Offer 55 - I. 二叉树的深度|104. 二叉树的最大深度:

输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。

样例 1:

给定二叉树 [3,9,20,null,null,15,7],
	
	3
   / \
  9  20
    /  \
   15   7
	
返回它的最大深度 3 。

提示:

  • 节点总数 <= 10000

分析

  • 面对这道算法题目,二当家的陷入了沉思。
  • 使用层序遍历或者递归都可以,感觉递归套娃大法更加直观。

题解

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 max_depth(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        match root {
            Some(root) => {
                1 + Solution::max_depth(root.borrow().left.clone()).max(Solution::max_depth(root.borrow().right.clone()))
            }
            _ => {
                0
            }
        }
    }
}

go

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func maxDepth(root *TreeNode) int {
    if root != nil {
		maxLeftDepth := maxDepth(root.Left)
		maxRightDepth := maxDepth(root.Right)
		if maxLeftDepth > maxRightDepth {
			return 1 + maxLeftDepth
		} else {
			return 1 + maxRightDepth
		}
	}
	return 0
}

c++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root) {
            return 1 + max(maxDepth(root->left), maxDepth(root->right));
        }
        return 0;
    }
};

java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if (root != null) {
			return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
		}
		return 0;
    }
}

python

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

class Solution:
    def maxDepth(self, root: TreeNode) -> int:
        if root:
            return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
        return 0


原题传送门:https://leetcode.cn/problems/er-cha-shu-de-shen-du-lcof/

原题传送门:https://leetcode.cn/problems/maximum-depth-of-binary-tree/


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


本文含有隐藏内容,请 开通VIP 后查看