Java判断二叉树是否平衡

标签 java iteration binary-tree binary-search-tree breadth-first-search

这是“破解编码面试”中的问题:

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.

书中只给出了递归的解决方案。我想出了一个使用 BFS 的迭代解决方案,只是想分享它。我进行了试运行,但想确保我没有犯错。我还想看看其他人认为他们可以如何改进它。

谢谢!

最佳答案

class Node
{
int data;
LinkedList<Node> children;
}

public static boolean isBalanced(Node root)
{
LinkedList<Node> queue = new LinkedList<Node>();
queue.offer(root);

int currentLevel = -1, toNextLevel = 0, toNextLevelTemp = 1;

int minLevel = Integer.MAX_VALUE, maxLevel = Integer.MIN_VALUE;

while(!queue.isEmpty())
{
    if(toNextLevel == 0)
    {
        currentLevel++;
        toNextLevel = toNextLevelTemp;
        toNextLevelTemp = 0;
    }

    Node temp = queue.poll();
    toNextLevel--;

    //if temp is a leaf, record its depth
    if(temp.children.size() == 0)   
    {
        if(currentLevel < minLevel)
            minLevel = currentLevel;

        if(currentLevel > maxLevel)
            maxLevel = currentLevel;
    }

    //do whatever with temp
    for(Node child: temp.children)
    {
        queue.add(child);
        toNextLevelTemp++;
    }
}

//if difference between minLevel and maxLevel is more than 1
if(maxLevel - minLevel > 1)
    return false;

return true;
}

关于Java判断二叉树是否平衡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28036765/

相关文章:

java - 如何替换 JTextPane 中的 StyledDocument

javascript - 如何正确迭代 JSON 对象?

python - 如何迭代Python列表并删除相似元素?

tree - 如何获取从根到二叉树上给定节点的路径?

c - 如何在C中删除二叉树中的元素?

java - Swing + MigLayout,其他组件的动态增长和收缩

java - 无法检查文件系统中是否存在具有德语名称的文件

java - Spring Data Jpa 和规范 - 如何处理 ManyToOne 和 ManyToMany 关系?

c# - 如何检测集合在迭代过程中是否被修改

r - 是否可以使用 R 获得分类树分析中节点的 p 值?