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;
    	}
    };
    

      

  • 相关阅读:
    Qt计算器开发(三):执行效果及项目总结
    [HNOI2019]校园旅行
    How to fix nuget Unrecognized license type MIT when pack
    How to fix nuget Unrecognized license type MIT when pack
    git 通过 SublimeMerge 处理冲突
    git 通过 SublimeMerge 处理冲突
    git 上传当前分支
    git 上传当前分支
    gif 格式
    gif 格式
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842280.html
Copyright © 2011-2022 走看看