二叉树的深度-LeetCode

题目:

在这里插入图片描述
原文链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/

思路:

  1. 就使用递归深度优先遍历就好了,如果当前结点非空,那么返回深度就默认+1
  2. 时间复杂度为O(n),因为每个结点只被访问一次

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    
    
    public int maxDepth(TreeNode root) {
    
    
        if(root==null){
    
    
            return 0;
        }else{
    
    
            return Math.max(maxDepth(root.left), maxDepth(root.right))+1;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_35221523/article/details/112645294