Maximum Depth of Binary Tree--二叉树的深度
原题:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. }};
晓东分析:
这其实是一个很基础的题目,稍微有点基础的同学应该都写过,所以也就不需要详细说明什么。这种题目使用递归的算法是最简单的,思路就是先求出左节点为根节点的二叉树的深度,再求出右节点为根节点的二叉树深度,然后看这两者谁大,大的那个加上1就是原来的二叉树的深度。
代码实现:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int maxDepth(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. int left_depth = 0; int right_depth = 0; if(NULL == root) return 0; left_depth = maxDepth(root->left); right_depth = maxDepth(root->right); return left_depth > right_depth ? left_depth + 1 : right_depth + 1; }};
执行结果:
Runtime: 44 ms
执行时间还是可以接收的。
希望大家有更好的算法能够提出来,不甚感谢。
若您觉得该文章对您有帮助,请在下面用鼠标轻轻按一下“顶”,哈哈~~·