本文主要是介绍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就行,这里需要注意的是空树也是平衡二叉树
代码:
public boolean isBalanced(TreeNode root) {if(root == null) {return true;}//如果左右结点高度差的绝对值大于1if(Math.abs(DFS(root.left) -DFS(root.right))>1) {return false;}return isBalanced(root.left)&&isBalanced(root.right);}//获取当前节点的高度public int DFS(TreeNode root) {if(root == null) {return 0;}int ldept = DFS(root.left);int rdept = DFS(root.right);return Math.max(ldept, rdept)+1;}
这篇关于LeetCode - balanced-binary-tree的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!