【LeetCode练习题】Maximum Depth of Binary Tree

Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

求二叉树的高度,即从根节点到叶节点上所有节点的数量。

解题思路:

这题是难度系数1,频率1的题目……用到的知识点是二叉树DFS(深度遍历)。

一个计数变量count,一个记录最大值变量max。

深度遍历的时候,遍历到的节点分三种情况:

  1. 叶节点。此时比较max和count的大小,将较大的那个赋值给max。
  2. 非叶节点,且有左节点无右节点,继续遍历其左节点,从左节点返回时要将count减1. 右节点不遍历了。
  3. 非叶节点,且有右节点无左节点,继续遍历其右节点,从右节点返回时要将count减1. 左节点不便利了。

max即为所求的最大深度。

代码如下:

class Solution {
public:
    int maxDepth(TreeNode *root) {
        int count = 0,max = 0;
        depth(root,count,max);
        return max;
    }
    
    void depth(TreeNode *root,int &count,int &max){
        if(root){
            if(!root->left && !root->right){
                count++;
                if(max < count)
                    max = count;
            }
            else{
                count++;
                if(root->left){
                    depth(root->left,count,max);
                    count--;
                }
                if(root->right){
                    depth(root->right,count,max);
                    count--;
                }
            }
        }
    }
};

 难怪难度系数是1,可以简单成这个样子:

class Solution {  
public:  
    int maxDepth(TreeNode *root) {  
        if(root == NULL) return 0;  
          
        int l = maxDepth(root->left);  
        int r = maxDepth(root->right);  
          
        return l > r ? l + 1 : r + 1;  
    }  
}; 
原文地址:https://www.cnblogs.com/4everlove/p/3662343.html