C++ 二叉树的最大深度 递归与非递归 [LeetCode]

题目:

给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回它的最大深度 3 。

链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree

递归做法类似DFS深度优先搜索,

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int high=0;
    int maxDepth(TreeNode* root) {
        if(root==nullptr)
        return 0;

        return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

非递归做法是层序遍历,加了计数而已

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int high=0;
    int maxDepth(TreeNode* root) {
        if(root==nullptr)
        return 0;
        int leng=0;
        queue<TreeNode *> vec;
        TreeNode * p=root;
        vec.push(p);
        while(vec.size())
        {
            leng++;
            int size=vec.size();
            for(int i=0;i<size;i++)
            {
                p=vec.front();
                vec.pop();
                if(p->left) vec.push(p->left);
                if(p->right) vec.push(p->right);
            }
        }
        return leng;
    }
};

 

posted @ 2021-09-26 15:00  北陌南旬  阅读(139)  评论(0)    收藏  举报