码迷,mamicode.com
首页 > 其他好文 > 详细

CC150 4.1

时间:2014-11-27 08:03:52      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:interview

4.1 Implement a function to check if a tree is balanced. For the purposes of this question, a balanced tree is defined to be a tree such that no two leaf nodes differ in distance from the root by more than one.


A balanced tree?

http://en.wikipedia.org/wiki/Self-balancing_binary_search_tree


Iterate the tree, track root-distance for all leaf nodes?


boolean isBalanceTree(Node root)
{
  List<Integer> leafDis = initList();
  visit(root, 0, leafDis);

  return max(leafDis) - min(leafDis) > 1;
}

private void visit(Node n, int curDis, List<Integer> leafDis)
{
  if (n.childrean == null)
    leafDis.add(curDis);
    
  for (Node child : n.children)
  {
    visit(child, curDis + 1, leafDis);
  }
}


CC150 4.1

标签:interview

原文地址:http://7371901.blog.51cto.com/7361901/1583039

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!