二叉树的最大深度(LintCode)

来源:互联网 发布:vb net入门教程pdf 编辑:程序博客网 时间:2024/05/16 06:25
题目来源:LintCode

原题地址:http://www.lintcode.com/zh-cn/problem/maximum-depth-of-binary-tree/

题目:

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的距离。

您在真实的面试中是否遇到过这个题? 
Yes
样例

给出一棵如下的二叉树:

  1 / \ 2   3   / \  4   5

这个二叉树的最大深度为3.

难度级别:
容易

思路分析:
遍历每个节点,返回该节点左右子树中深度较大的一个

实现代码:
/** * Definition of TreeNode: * class TreeNode { * public: *     int val; *     TreeNode *left, *right; *     TreeNode(int val) { *         this->val = val; *         this->left = this->right = NULL; *     } * } */class Solution{public:/*** @param root: The root of binary tree.* @return: An integer*/int maxDepth(TreeNode *root){if (root == NULL){return 0;}int left = maxDepth(root->left);int right = maxDepth(root->right);return (left > right) ? left + 1 : right + 1;}};



代码说明:
需要注意的是,在返回值时,需要将左右子树的深度加1,这个代表此节点自己的位置。
如果没有+1操作,会得到错误的答案。
0 0
原创粉丝点击