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

      

  • 相关阅读:
    PHP返回XML与JSON数据
    Canvas学习-1
    PHP与cURL
    PHP调用SOAP Webservice
    Ubuntu查找文件是否安装
    API Centeric Web Application论文
    Git学习2
    An invalid character [32] was present in the Cookie value
    关于eclipse项目的x号报错的一些问题
    关于eclipse的项目前有感叹号和errors exist in required project相关问题
  • 原文地址:https://www.cnblogs.com/csudanli/p/5842280.html
Copyright © 2020-2023  润新知