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.

    大致题意

    判断一棵树是不是平衡树

    题解

    题目类型:dfs

    基本的dfs题目,遍历节点的同时计算左右子树的高度,借由此来判断是否时平衡树

    代码如下

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int depth (TreeNode *root) {
            if (root == NULL) return 0;
            return max (depth(root -> left), depth (root -> right)) + 1;
        }
    
        bool isBalanced (TreeNode *root) {
            if (root == NULL) return true;
            
            int left=depth(root->left);
            int right=depth(root->right);
            
            return abs(left - right) <= 1 && isBalanced(root->left) && isBalanced(root->right);
        }
    };
  • 相关阅读:
    呵呵

    HDU 1878 欧拉回路
    HDU 3293 sort
    HDU 2714 ISBN
    神秀作偈
    大学之道
    写给自己过去疯狂的一年(2)(写在一个特别的时候)
    这几天我的生活就是这样的
    学习和研究计划
  • 原文地址:https://www.cnblogs.com/twodog/p/12137699.html
Copyright © 2011-2022 走看看