博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode 104 Maximum Depth of Binary Tree二叉树求深度
阅读量:7235 次
发布时间:2019-06-29

本文共 2497 字,大约阅读时间需要 8 分钟。

Maximum Depth of Binary Tree

Total Accepted: 63668 Total Submissions: 141121 My Submissions
Question Solution

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

我的解决方案:

这里写图片描述

/** * 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(NULL == root)            return 0;        int depth_l = maxDepth(root->left);        int depth_r = maxDepth(root->right);        return depth_l > depth_r  ? depth_l + 1:depth_r + 1;    }};

一行代码的解法:

int maxDepth(TreeNode *root){    return root == NULL ? 0 : max(maxDepth(root -> left), maxDepth(root -> right)) + 1;}

不用递归的解法:Breadth-first-search

int maxDepth(TreeNode *root){    if(root == NULL)        return 0;    int res = 0;    queue
q; q.push(root); while(!q.empty()) { ++ res; for(int i = 0, n = q.size(); i < n; ++ i) { TreeNode *p = q.front(); q.pop(); if(p -> left != NULL) q.push(p -> left); if(p -> right != NULL) q.push(p -> right); } } return res;}

不用递归的解法2

int maxDepth(TreeNode *root){    if (root == NULL) return 0;    stack
gray; stack
depth; int out = 0; gray.push(root); depth.push(1); while (!gray.empty()) { TreeNode *tmp = gray.top(); int num = depth.top(); gray.pop(); depth.pop(); if (tmp->left == NULL && tmp->right == NULL) { out = num > out ? num : out; } else { if (tmp->left != NULL) { gray.push(tmp->left); depth.push(num + 1); } if (tmp->right != NULL) { gray.push(tmp->right); depth.push(num + 1); } } } return out;}

python 的解决方案:

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @return an integer    def maxDepth(self, root):        def maxDepthHelper(root):            if not root: return 0            return max(1+maxDepthHelper(root.left), 1+maxDepthHelper(root.right))        return maxDepthHelper(root)
你可能感兴趣的文章
如何监控和保护Linux下进程安全
查看>>
linux kvm虚拟机配置及常见问题处理
查看>>
安装Heartbeat-glue,绝对全,自己亲自操作的。
查看>>
zip压缩工具、tar打包、打包并压缩
查看>>
接口中图片的接收
查看>>
android不要全屏保留状态栏
查看>>
java.lang.UnsupportedClassVersionError
查看>>
捕捉到的CRS错误提示
查看>>
Linux系统安装需要注意几处
查看>>
mysql读写分离
查看>>
创建远程git仓库
查看>>
linux 文件查找帮助命令 , 查看网络链接信息, 历史命令
查看>>
centos 分区扩容
查看>>
ActiveMQ Tips
查看>>
linux日常维护(网络相关,防火墙,netfirter介绍,netfirter语法)
查看>>
keepalived双机热备nginx
查看>>
深入Nginx优化
查看>>
Collections的简单学习
查看>>
简介Valgrind工具包功能
查看>>
Chrome开发者工具的小技巧
查看>>