104. 二叉树的最大深度

122 阅读1分钟

104. 二叉树的最大深度 - 力扣(LeetCode)

先找到叶子节点,即左右子树都为空,那么此时肯定已经统计出来树深了,把树深返回即可。

树深的统计方法:左子树不为空就count++,右子树不为空就count++ #计数法


class Solution {
public:


     int  dfs(TreeNode* root,int& count)
     {
         if(root==nullptr)return count;

        if(!root->left && !root->right)return count;

        if(root->left)
        {
            count++;
            dfs(root->left,count);
        }
        
        if(root->right)
        {
            count++;
            dfs(root->right,count);
        }

     }
    int maxDepth(TreeNode* root) {
     
      int count=0;
     return  dfs(root,count);
        


        
    }
};

逻辑错误

1.没有算上根节点

2.把左子树深度都返回了:

image.png image.png






后序递归遍历

二叉树的树深: 从根节点到叶子节点的路径和。

二叉树的树高:从叶子节点到根节点的路径和;

当要求二叉树的最大树深时,实际上 最大树深就是二叉树的高度

image.png

求树高我们一般用后序,求树深一般用前序

这道题因为是最大树深,所以就可以用后序求树深。

即用左右中的顺序遍历,根节点最后处理。

我们先左子树开始,递归向下遍历,此时走到空了,然后我们从叶子节点开始向上返回。

叶子节点是1,返回给父亲节点之后,父亲节点在子节点的树深上+1就是父亲节点的树深。

image.png

image.png





回溯法

image.png

回溯法