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

    这个题目的意思是,如果一个二叉树树的任何节点的左右子树的深度之差不大于1,就是一个高度平衡的二叉树,求你判断一棵树是否是高度平衡的二叉树

    我的思路是,如果遍历到某个节点时,它的左右子树深度之差大于1,则返回-1,否则返回以这个节点为跟时树的高度,这样遍历完全后,即可判断是否是平衡的二叉树

    /**
     * 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 depthFirstSearch(TreeNode *root)
    	{
    		if (root == NULL)return 0;
    		int leftdep = depthFirstSearch(root->left);
    		int rightdep=depthFirstSearch(root->right);
    		if (abs(leftdep - rightdep) > 1|| leftdep == -1 || rightdep == -1)return -1;
    		return leftdep > rightdep ? leftdep + 1 : rightdep + 1;
    	}
    	bool isBalanced(TreeNode* root) {
    		if (depthFirstSearch(root) == -1)return false;
    		else return true;
    	}
    };
    

      

  • 相关阅读:
    Java中 Jwt
    Python中Jwt
    jwt流程
    Vue Demons
    Vue基础
    Mysql
    MongoDb
    2020/03/07-基础复习day_02
    2020/03/07-基础复习day_01
    基于springboot+dubbo的简易分布式小Demo
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842280.html
Copyright © 2011-2022 走看看