二叉树的最大深度

来源:互联网 发布:w7 mysql更改密码 编辑:程序博客网 时间:2024/06/07 14:37

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

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

样例

给出一棵如下的二叉树:

  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 max(int x,int y)
     {
         if(x>y)return x;
         else return y;
     }
    int maxDepth(TreeNode *root) {
        // write your code here
        if(root==NULL)return 0;
        else {
            int x=maxDepth(root->left)+1;
            int y=maxDepth(root->right)+1;
            int z=max(x,y);
            return z;
        }
    }
};

原创粉丝点击