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

     
     思路: 后序遍历二叉树。同时判断以该节点为根的子树是否是平衡树。如果是则返回该子树的高度,如果不是返回-1
    相关题目:《剑指offer》面试题39
    /**
     * 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:
        bool isBalanced(TreeNode* root) {
            if (root == NULL) return true;
            
            if (depth(root) == -1) {
                return false;
            } else {
                return true;
            }
        }
        
        int depth(TreeNode* root) {
            if (root == NULL) return 0;
            
            int left_depth = depth(root->left);
            if (left_depth == -1) return -1;
            int right_depth = depth(root->right);
            if (right_depth == -1) return -1;
            
            if (abs(left_depth - right_depth) > 1) return -1;
            
            return max(left_depth, right_depth) + 1;
        }
        
    
    };
  • 相关阅读:
    可持久化线段树学习笔记
    GDI+学习之路
    tcpdump——分析tcp关闭4次过程
    nasm过程调用
    ios学习:NSURLConnection 和 Json数据解析
    ios学习:文件简单读写
    JSONP原理及其简单封装
    JSP使用JSTL
    JDBC
    Apache无法正常启动的原因
  • 原文地址:https://www.cnblogs.com/vincently/p/4716381.html
Copyright © 2011-2022 走看看