Leetcode:104. 二叉树的最大深度

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

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

解题思路:

递归。从根节点开始访问,当前深度为1。递归查询左子树的最大深度depth_left以及右子树的最大深度depth_right。假设当前层的深度为depth,那么计算得到的树的最大深度为depth=depth+max(depth_left,depth_right)。应当注意的是当访问完左子树后,注意恢复当前层的初始数据,才能访问右子树。算法的时间复杂度为树的规模(n)。

                                    

C++代码
#define hasLChild(x) (!(x->left==NULL))
#define hasRChild(x) (!(x->right==NULL))
#define hasChild(x) (hasLChild(x)||hasRChild(x))
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        DFS(root);
        return depth;
    }
    void DFS(TreeNode* root) {
        if (hasChild(root)) depth++;
        int l = depth, r = depth, sgn = depth;
        if (root->left != NULL) {
            DFS(root->left);
            l = depth;
        }
        
        if (root->right != NULL) {
            depth = sgn;
            DFS(root->right);
            r = depth;
        }
        depth = (l > r ? l : r);
    }
private:
    int depth = 1;
};

猜你喜欢

转载自blog.csdn.net/qq_23523409/article/details/83748750