【问题标题】:how to check if a tree is complete?如何检查一棵树是否完整?
【发布时间】:2015-11-09 01:15:49
【问题描述】:

这是我的 A 类二叉搜索树:

public class BinarySearchTree {

        class BSTNode {
                int data;
                BSTNode rchild;
                BSTNode lchild;

                //constructor
                public BSTNode(int n){
                        data=n;
                        lchild=rchild=null;

                }
        }

        private BSTNode root;
        private int size;

        public BinarySearchTree() {
                root = null;
                size = -1;
        }

        public boolean insert(int n) {
                if (root == null)
                        root = new BSTNode(n);
                else
                        insert(n, root);
                return true;
        }

        private void insert(int n, BSTNode r) {

                if (r.data > n)
                        if (r.lchild == null)
                                r.lchild = new BSTNode(n);
                        else
                                insert(n, r.lchild);
                else

                if (r.data < n)
                        if (r.rchild == null)
                                r.rchild = new BSTNode(n);
                        else
                                insert(n, r.rchild);


        }
}

实际上,我发现编写一个检查我的树是否为完全二叉树的方法有困难。有人可以为我提供解决方案吗?

我将遵循这个定义: 完全二叉树:除最后一层外,每一层都被完全填满,所有节点左对齐。

【问题讨论】:

  • 欢迎来到本站!到目前为止,您尝试过什么?

标签: java recursion binary-search-tree


【解决方案1】:

您将不得不为您的BSTNode 的实现稍作修改,但我相信这应该符合您的需求。基本思想是递归遍历树并确保每个子树都满足“完整”属性。

boolean checkBinaryTreeCompleteness(TreeNode root) {
  if (root != null) {
    if (root.right == null && root.left == null) {
      return true;
    }
    if (root.right != null && root.left != null) {
      return checkBinaryTreeCompleteness(root.left) && checkBinaryTreeCompleteness(root.right);
    }
  }
  return false;
}

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2016-01-24
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多