小言_互联网的博客

【LintCode 题解】小米面试算法题:平衡二叉树

514人阅读  评论(0)

题目描述

给定一个二叉树,确定它是高度平衡的。对于这个问题,一棵高度平衡的二叉树的定义是:一棵二叉树中每个节点的两个子树的深度相差不会超过1。 

点击在线测评代码


  
  1. 样例 1:
  2. 输入: tree = { 1, 2, 3}
  3. 输出: true
  4. 样例解释:
  5. 如下,是一个平衡的二叉树。
  6. 1
  7. / \
  8. 2 3
  9. 样例 2:
  10. 输入: tree = { 3, 9, 20, #,#,15,7}
  11. 输出: true
  12. 样例解释:
  13. 如下,是一个平衡的二叉树。
  14. 3
  15. / \
  16. 9 20
  17. / \
  18. 15 7
  19. 样例 2:
  20. 输入: tree = { 1, #,2,3,4}
  21. 输出: false
  22. 样例解释:
  23. 如下,是一个不平衡的二叉树。 1的左右子树高度差 2
  24. 1
  25. \
  26. 2
  27. / \
  28. 3 4

题解

在树上做一次DFS,记录以每个点为根的子树高度。

解法2中提供了更简洁的方法,将子树高度作为返回值返回。

对于大厂面试中高频出现的经典题,我们需要了解它的不同解法,有的大厂不喜欢你一上来就秒掉题目,而更重视你一步步根据题目优化解法,最后得到最优解的解题思路和过程。

另外即使运气真的很不好碰到了新题,做过的高频题也会激发你解题的思路。


  
  1. /**
  2. * This reference program is provided by @jiuzhang.com
  3. * Copyright is reserved. Please indicate the source for forwarding
  4. */
  5. // Version 1: with ResultType
  6. /**
  7. * Definition of TreeNode:
  8. * public class TreeNode {
  9. * public int val;
  10. * public TreeNode left, right;
  11. * public TreeNode(int val) {
  12. * this.val = val;
  13. * this.left = this.right = null;
  14. * }
  15. * }
  16. */
  17. class ResultType {
  18. public boolean isBalanced;
  19. public int maxDepth;
  20. public ResultType(boolean isBalanced, int maxDepth) {
  21. this.isBalanced = isBalanced;
  22. this.maxDepth = maxDepth;
  23. }
  24. }
  25. public class Solution {
  26. /**
  27. * @param root: The root of binary tree.
  28. * @return: True if this Binary tree is Balanced, or false.
  29. */
  30. public boolean isBalanced(TreeNode root) {
  31. return helper(root).isBalanced;
  32. }
  33. private ResultType helper(TreeNode root) {
  34. if (root == null) {
  35. return new ResultType( true, 0);
  36. }
  37. ResultType left = helper(root.left);
  38. ResultType right = helper(root.right);
  39. // subtree not balance
  40. if (!left.isBalanced || !right.isBalanced) {
  41. return new ResultType( false, - 1);
  42. }
  43. // root not balance
  44. if (Math.abs(left.maxDepth - right.maxDepth) > 1) {
  45. return new ResultType( false, - 1);
  46. }
  47. return new ResultType( true, Math.max(left.maxDepth, right.maxDepth) + 1);
  48. }
  49. }
  50. // Version 2: without ResultType
  51. public class Solution {
  52. public boolean isBalanced(TreeNode root) {
  53. return maxDepth(root) != - 1;
  54. }
  55. private int maxDepth(TreeNode root) {
  56. if (root == null) {
  57. return 0;
  58. }
  59. int left = maxDepth(root.left);
  60. int right = maxDepth(root.right);
  61. if (left == - 1 || right == - 1 || Math.abs(left-right) > 1) {
  62. return - 1;
  63. }
  64. return Math.max(left, right) + 1;
  65. }
  66. }

 


转载:https://blog.csdn.net/JiuZhang_ninechapter/article/details/104520421
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场