当前位置: 移动技术网 > IT编程>开发语言>Java > Java实现求二叉树的深度和宽度

Java实现求二叉树的深度和宽度

2019年07月22日  | 移动技术网IT编程  | 我要评论

这个是常见的对二叉树的操作。总结一下:

设节点的数据结构,如下:

复制代码 代码如下:

class treenode {
    char val;
    treenode left = null;
    treenode right = null;

    treenode(char _val) {
        this.val = _val;
    }
}

1.二叉树深度

  这个可以使用递归,分别求出左子树的深度、右子树的深度,两个深度的较大值+1即可。

复制代码 代码如下:

// 获取最大深度
    public static int getmaxdepth(treenode root) {
        if (root == null)
            return 0;
        else {
            int left = getmaxdepth(root.left);
            int right = getmaxdepth(root.right);
            return 1 + math.max(left, right);
        }
    }

2.二叉树宽度

  使用队列,层次遍历二叉树。在上一层遍历完成后,下一层的所有节点已经放到队列中,此时队列中的元素个数就是下一层的宽度。以此类推,依次遍历下一层即可求出二叉树的最大宽度。

复制代码 代码如下:

// 获取最大宽度
    public static int getmaxwidth(treenode root) {
        if (root == null)
            return 0;

        queue<treenode> queue = new arraydeque<treenode>();
        int maxwitdth = 1; // 最大宽度
        queue.add(root); // 入队

        while (true) {
            int len = queue.size(); // 当前层的节点个数
            if (len == 0)
                break;
            while (len > 0) {// 如果当前层,还有节点
                treenode t = queue.poll();
                len--;
                if (t.left != null)
                    queue.add(t.left); // 下一层节点入队
                if (t.right != null)
                    queue.add(t.right);// 下一层节点入队
            }
            maxwitdth = math.max(maxwitdth, queue.size());
        }
        return maxwitdth;
    }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网