Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java检查二叉树是否平衡_Java_Iteration_Binary Tree_Binary Search Tree_Breadth First Search - Fatal编程技术网

Java检查二叉树是否平衡

Java检查二叉树是否平衡,java,iteration,binary-tree,binary-search-tree,breadth-first-search,Java,Iteration,Binary Tree,Binary Search Tree,Breadth First Search,这是“破解编码面试”中的一个问题: 实现一个函数来检查树是否平衡。出于这个问题的目的,平衡树被定义为这样的树,即两个叶节点与根的距离相差不超过一个 这本书只给出了一个递归的解决方案。我提出了一个使用BFS的迭代解决方案,只是想和大家分享一下。我确实试过了,但我想确保我没有弄错。我还想看看其他人如何认为他们能够改进它 谢谢 类节点 class Node { int data; LinkedList<Node> children; } public static boolean isB

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

实现一个函数来检查树是否平衡。出于这个问题的目的,平衡树被定义为这样的树,即两个叶节点与根的距离相差不超过一个

这本书只给出了一个递归的解决方案。我提出了一个使用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;
}
{ int数据; 社交网站儿童; } 公共静态布尔值isBalanced(节点根) { LinkedList队列=新建LinkedList(); queue.offer(根); int currentLevel=-1,toNextLevel=0,toNextLevelTemp=1; int minLevel=Integer.MAX\u值,maxLevel=Integer.MIN\u值; 而(!queue.isEmpty()) { if(toNextLevel==0) { currentLevel++; toNextLevel=toNextLevelTemp; toNextLevelTemp=0; } Node temp=queue.poll(); 色调层次--; //如果temp是一片叶子,则记录其深度 如果(临时子项大小()==0) { 如果(当前级别<最小级别) minLevel=当前级别; 如果(currentLevel>maxLevel) maxLevel=currentLevel; } //用temp做什么都行 用于(节点子节点:临时子节点) { 添加(子级); toNextLevelTemp++; } } //如果minLevel和maxLevel之间的差异大于1 如果(最大级别-最小级别>1) 返回false; 返回true; }
我花的时间比我预期的要长,但这个解决方案很有效,请随意让我的代码更漂亮,在我的代码正常工作后,我做了最少的润色

/* Returns true if binary tree with root as root is height-balanced */
    boolean isBalanced(Node root) {
        if(root == null) return false;

        Deque<Integer> heights = new LinkedList<>();
        Deque<Node> trail = new LinkedList<>();
        trail.push(root);

        Node prev = root; //set to root not null to not confuse when root is misisng children

        while(!trail.isEmpty()) {
            Node curr = trail.peek(); //get the next node to process, peek because we need to maintain trail until we return

            //if we just returned from left child
            if (curr.left == prev) {
                if(curr.right != null) trail.push(curr.right); //if we can go right go
                else {
                    heights.push(-1); //otherwise right height is -1 does not exist and combine heights
                    if(!combineHeights(heights)) return false;
                    trail.pop(); //back to parent
                }
            }
            //if we just returned from right child
            else if (curr.right == prev) {
                if(!combineHeights(heights)) return false;
                trail.pop(); //up to parent
            }
            //this came from a parent, first thing is to visit the left child, or right if no left
            else {
                if(curr.left != null) trail.push(curr.left);
                else {
                    if (curr.right != null) {
                        heights.push(-1); //no left so when we combine this node left is 0
                        trail.push(curr.right); //since we never go left above logic does not go right, so we must here
                    }
                    else { //no children set height to 1
                        heights.push(0);
                        trail.pop(); //back to parent
                    }
                }
            }

            prev = curr;
        }

        return true;
    }

    //pop both previous heights and make sure they are balanced, if not return false, if so return true and push the greater plus 1
    private boolean combineHeights(Deque<Integer> heights) {
        int rightHeight = heights.pop();
        int leftHeight = heights.pop();

        if(Math.abs(leftHeight - rightHeight) > 1) return false;
        else heights.push(Math.max(leftHeight, rightHeight) + 1);
        return true;
    }
/*如果根为根的二叉树高度平衡,则返回true*/
布尔isBalanced(节点根){
if(root==null)返回false;
Deque heights=新链接列表();
Deque trail=new LinkedList();
推(根);
Node prev=root;//设置为root not null,以便在root为MISING子级时不会混淆
而(!trail.isEmpty()){
Node curr=trail.peek();//获取下一个要处理的节点,peek,因为我们需要在返回之前保持trail
//如果我们刚从左边的孩子回来
如果(当前左侧==上一个){
if(curr.right!=null)trail.push(curr.right);//如果我们可以直接走
否则{
heights.push(-1);//否则右边的heights是-1,并且不存在合并高度
如果(!组合权重(高度))返回false;
trail.pop();//返回到父级
}
}
//如果我们从合适的孩子那里回来
else if(当前右侧==上一个){
如果(!组合权重(高度))返回false;
trail.pop();//转到父级
}
//这来自一位家长,第一件事就是看望左边的孩子,如果没有左边的话,还是右边的
否则{
if(curr.left!=null)trail.push(curr.left);
否则{
如果(当前右侧!=null){
heights.push(-1);//没有左边,所以当我们合并这个节点时,左边是0
trail.push(curr.right);//因为我们从不向左走,所以逻辑就不会向右走,所以我们必须在这里
}
else{//没有子项将高度设置为1
高度。推(0);
trail.pop();//返回到父级
}
}
}
上一次=当前;
}
返回true;
}
//弹出前两个高度并确保它们平衡,如果不返回false,如果返回true并按下较大值加1
专用布尔组合权重(德克高度){
int rightHeight=heights.pop();
int leftHeight=heights.pop();
if(Math.abs(leftHeight-rightHeight)>1)返回false;
else HEIGHT.push(数学最大值(左高、右高)+1);
返回true;
}

变量“toNextLevel”记录下一个级别之前的节点数。“toNextLevelTemp”统计仍处于当前级别时添加到队列中的节点数,并在级别增加时将其值赋给“toNextLevel”。我认为这不起作用,想想如果一侧没有子节点,它将被忽略,这只考虑离开,如果节点的子节点之一为空,那么另一个是不允许在平衡树中有孩子的,我会搞乱它,看看我是否能找到一个直观的方法将其集成到这个解决方案中