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

    Note: A leaf is a node with no children.

    Example:

    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7

    return its depth = 3.

    求二叉树的最大深度。最大深度就是从根节点到叶节点的最长路径。

    解法1: DFS

    解法2: 层序遍历,总层数就是最大深度。

    Java:DFS

    public class Solution {
        public int maxDepth(TreeNode root) {
            return root == null ? 0 : (1 + Math.max(maxDepth(root.left), maxDepth(root.right)));
        }
    }
    

    Java: Level Travesal

    public class Solution {
        public int maxDepth(TreeNode root) {
            if (root == null) return 0;
            int res = 0;
            Queue<TreeNode> q = new LinkedList<>();
            q.offer(root);
            while (!q.isEmpty()) {
                ++res;
                int n = q.size();
                for (int i = 0; i < n; ++i) {
                    TreeNode t = q.poll();
                    if (t.left != null) q.offer(t.left);
                    if (t.right != null) q.offer(t.right);
                }
            }
            return res;
        }
    }
    

    Python: DFS

    class Solution:
        # @param root, a tree node
        # @return an integer
        def maxDepth(self, root):
            if root is None:
                return 0
            else:    
                return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
    

    C++: DFS

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (!root) return 0;
            return 1 + max(maxDepth(root->left), maxDepth(root->right));
        }
    };
    

    C++:

    class Solution {
    public:
        int maxDepth(TreeNode* root) {
            if (!root) return 0;
            int res = 0;
            queue<TreeNode*> q;
            q.push(root);
            while (!q.empty()) {
                ++res;
                int n = q.size();
                for (int i = 0; i < n; ++i) {
                    TreeNode *t = q.front(); q.pop();
                    if (t->left) q.push(t->left);
                    if (t->right) q.push(t->right);
                }
            }
            return res;
        }
    };
    

     

    类似题目:

    [LeetCode] 366. Find Leaves of Binary Tree 找二叉树的叶节点

    [LeetCode] 310. Minimum Height Trees 最小高度树

    [LeetCode] 545. Boundary of Binary Tree 二叉树的边界

     

    All LeetCode Questions List 题目汇总

      

      

  • 相关阅读:
    动态规划_leetcode70
    动态规划_leetcode64
    动态规划_leetcode63
    PHP处理base64编码字符串
    PHP解决h5页面跨域
    PHP对象转数组
    jQuery 正则
    mysql重置密码
    yii框架学习(获取插入后的id)
    nginx 之 root和alias
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8553363.html
Copyright © 2011-2022 走看看