美文网首页
二叉树的最小、最大深度以及平衡二叉树

二叉树的最小、最大深度以及平衡二叉树

作者: juexin | 来源:发表于2017-04-18 17:27 被阅读0次

**111. Minimum Depth of Binary Tree **
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
代码如下:

class Solution {
public:
    int minDepth(TreeNode* root) {
        if(root==NULL)
            return 0;
        int left = minDepth(root->left);
        int right = minDepth(root->right);
        if(root->left==NULL&&root->right==NULL)
            return 1;
        if(root->left==NULL)
            left = INT_MAX;
        if(root->right==NULL)
            right = INT_MAX;
        return left<right ? left + 1 : right + 1;
    }
};

**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.

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==NULL)
          return 0;
        int left = maxDepth(root->left);
        int right = maxDepth(root->right);
        return left>right ? left+1:right+1;
    }
};

**110. Balanced Binary Tree **
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
代码如下:

class Solution {
public:
    bool isBalanced(TreeNode* root) {
        if(root==NULL)
          return true;
        int mLeft = maxDepth(root->left);
        int mRight = maxDepth(root->right);
        
        if(abs(mLeft-mRight)>1)
          return false;
        else
          return isBalanced(root->left)&&isBalanced(root->right);
    }
    int maxDepth(TreeNode* node)
    {
        if(node==NULL)
          return 0;
        int left = maxDepth(node->left);
        int right = maxDepth(node->right);
        return left>right? left+1:right+1;
    }
};

相关文章

  • 二叉树面试题基本问题

    二叉树的最大深度与最小深度 二叉树的最大深度 最大深度是指二叉树根节点到该树叶子节点的最大路径长度。而最小深度自然...

  • LeetCode 深度优先遍历

    概述 前言 104 二叉树的最大深度【简单】 111 二叉树的最小深度 【简单】 124 二叉树中的最大路径和 【...

  • 111. Minimum Depth of Binary Tre

    题目 给定一个二叉树,求二叉树最小深度 解析 一个二叉树的最小深度,就是求左子树最小深度或者右子树最小深度,然后加...

  • 判断一个树是否是BST 求一棵平衡二叉树的最小深度 判断一棵二叉树是否高度平衡

  • 二叉树

    深度优先遍历 递归 DFS 广度优先遍历 递归BFS 二叉树的最大最小深度 判断二叉树是否中轴对称

  • 104. 二叉树的最大深度

    二叉树的最大深度难度不大,关键是递归,以及递归停止条件要写清楚104. 二叉树的最大深度

  • 二叉树数据结构及其算法操作(Java)

    二叉树的定义 向二叉树中插入节点 搜索二叉树中最大值和最小值 搜索二叉树的深度(height)和节点数(size)...

  • 树的深度

    计算一颗二叉树的最大深度和最小深度public int maxDepth(TreeNode root){if(ro...

  • Swift - LeetCode - 二叉树的最小深度

    题目 二叉树的最小深度 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。...

  • Leetcode 111 二叉树的最小深度

    二叉树的最小深度 题目 给定一个二叉树,找出其最小深度。 最小深度是从根节点到最近叶子节点的最短路径上的节点数量。...

网友评论

      本文标题:二叉树的最小、最大深度以及平衡二叉树

      本文链接:https://www.haomeiwen.com/subject/uzhqzttx.html