zoukankan      html  css  js  c++  java
  • 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.

    思路:深搜

    如果节点为空,返回0,;如果不为空,要看是否左右孩子节点是否存在,不存在直接返回1.

    然后剩下有说明至少存在一个,左节点在,就定义left加上1.右节点同样处理。


    代码:

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
     //本质上方法一样,只是通过实践竟然不同
    class Solution1 {
    //https://leetcode.com/problems/maximum-depth-of-binary-tree/
    public:
        int maxDepth(TreeNode* root) {
            if(root==NULL){
                return 0;
            }
            if(root->left==NULL&&root->right==NULL){
                return 1;
            }
    
            int left=0;
            if(root->left){
                left=maxDepth(root->left)+1;
            }
    
            int right=0;
            if(root->right){
                right=maxDepth(root->right)+1;
            }
    
            return max(left,right);
        }
    };
    
    class Solution2 {
    public:
        int count=1;
        int maxDepth(TreeNode* root) {
            if(root==NULL){
                return 0;
            }
            //int left=maxDepth(root->left);
            //int right=maxDepth(root->right);
            return max(maxDepth(root->left)+1,maxDepth(root->right)+1);
        }
    };


  • 相关阅读:
    Struts2.5 利用Ajax将json数据传值到JSP
    io/nio
    Elasticsearch 、 Logstash以及Kibana 分布式日志
    zookeeper
    mybatis
    Kubemetes
    线程池
    @Builder
    jdk命令行工具系列
    什么是分布式事务
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519882.html
Copyright © 2011-2022 走看看