博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Balanced Binary Tree --判断平衡二叉树(重重)
阅读量:4108 次
发布时间:2019-05-25

本文共 788 字,大约阅读时间需要 2 分钟。

问题:

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.

解答:

可以根据定义 采用递归的方式解答,但是递归次数太多容易超时,问题的关键在于如果快速的得到树的深度,而不是每次都遍历,这里采用的一个方法是同过isbalancde函数每次同时返回一个树的深度。

参考:h

代码:

*/class Solution {public:    bool isBalanced(TreeNode *root) {		int deep = 0;		return isBalanced(root, &deep);		    }    bool isBalanced(TreeNode *root, int *deep)    {		if(root == NULL)		{			*deep = 0;			return true;		}		int left, right;		if(isBalanced(root->left, &left) && isBalanced(root->right, &right))		{			int diff = left - right;			if(diff <= 1 && diff >= -1)			{				*deep = 1 + (left > right? left:right);				return true;			}		}		return false;    }};

转载地址:http://mktsi.baihongyu.com/

你可能感兴趣的文章
C# 发HTTP请求
查看>>
初试visual studio2012的新型数据库LocalDB
查看>>
启动 LocalDB 和连接到 LocalDB
查看>>
Palindrome Number --回文整数
查看>>
Reverse Integer--反转整数
查看>>
Container With Most Water --装最多水的容器(重)
查看>>
Longest Common Prefix -最长公共前缀
查看>>
Letter Combinations of a Phone Number
查看>>
Single Number II --出现一次的数(重)
查看>>
Valid Parentheses --括号匹配
查看>>
Generate Parentheses--生成匹配括号(重)
查看>>
Remove Element--原地移除重复元素
查看>>
Remove Duplicates from Sorted Array--从有序数组中移除重复元素
查看>>
Count and Say
查看>>
Gas Station
查看>>
Palindrome Partitioning --回文切割 深搜(重重)
查看>>
Valid Palindrome 简单的回文判断
查看>>
Pascal's Triangle -- 生成杨辉三角
查看>>
Pascal's Triangle II 生成杨辉三角中的某行
查看>>
Minimum Depth of Binary Tree -- 二叉树的最小深度 DFS 加剪枝
查看>>