博客
关于我
leetcode 543. Diameter of Binary Tree
阅读量:306 次
发布时间:2019-03-04

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

题目概述

解题思路

这道题的思路就是:比较树中各个节点的左右子节点长度之和谁最大。通过递归地求解即可实现。时间复杂度可以控制在O(N)。

这道题的重点在于避免多次遍历一棵树。

解法性能

示例代码

class Solution {public:    int depth(TreeNode *root, int &ans)    {        if(root == NULL)            return 0;        int L_depth = 0, R_depth = 0;        if(root->left)            L_depth = 1 + depth(root->left, ans);        if(root->right)            R_depth = 1 + depth(root->right, ans);        ans = max(L_depth + R_depth, ans);                return max(L_depth, R_depth);    }        int diameterOfBinaryTree(TreeNode* root)     {        int res = 0;        depth(root, res);        return res;    }};

 

转载地址:http://zzaq.baihongyu.com/

你可能感兴趣的文章
STL教程:C++ STL快速入门(非常详细)
查看>>
MySQL中索引与视图的用法与区别详解
查看>>
【论文泛读03】卷积LSTM网络:一种短时降雨量预测的机器学习方法
查看>>
中科大-凸优化 笔记(lec45)-强凸性等价不等式
查看>>
【论文泛读29】关系抽取:卷积神经网络的视角
查看>>
Python中JSON的基本使用
查看>>
程序员建议(忘记从哪里转的了,反正是csdn上的一个兄弟)
查看>>
【学习笔记】欧拉函数,欧拉公式
查看>>
Python3序列
查看>>
React中设置404页面
查看>>
BootstrapValidator手动触发部分验证
查看>>
vue调试工具vue-devtools安装及使用
查看>>
CSS总结div中的内容垂直居中的四种方法
查看>>
[BZOJ4878]挑战NP-Hard
查看>>
vue指令之v-for
查看>>
[CF1278F]Cards
查看>>
用postman测试url参数
查看>>
Vue的is属性
查看>>
vue组件传参 props default 数组/对象的默认值应当由一个工厂函数返回
查看>>
vue爬坑之 父组件向子组件异步传参 子组件中拿不到值的解决方法
查看>>