BinaryTree实现

二叉树结点类实现

// BinaryNode class; stores a node in a tree.
//
// *******************PUBLIC OPERATIONS**********************
// int size( )            --> Return size of subtree at node
// int height( )          --> Return height of subtree at node
// void printPostOrder( ) --> Print a postorder tree traversal
// void printInOrder( )   --> Print an inorder tree traversal
// void printPreOrder( )  --> Print a preorder tree traversal
// BinaryNode duplicate( )--> Return a duplicate tree

/**
 * Binary node class with recursive routines to
 * compute size and height.
 */
public final class BinaryNode<AnyType> 
{
    public BinaryNode( )
    {
        this( null, null, null );
    }
    
    public BinaryNode( AnyType theElement, BinaryNode<AnyType> lt, BinaryNode<AnyType> rt )
    {
        element = theElement;
        left    = lt;
        right   = rt;
    }

    /**
     * Return the size of the binary tree rooted at t.
     */
    public static <AnyType> int size( BinaryNode<AnyType> t )
    {
        if( t == null )
            return 0;
        else
            return 1 + size( t.left ) + size( t.right );
    }

    /**
     * Return the height of the binary tree rooted at t.
     */
    public static <AnyType> int height( BinaryNode<AnyType> t )
    {
        if( t == null )
            return -1;
        else
            return 1 + Math.max( height( t.left ), height( t.right ) );
    }

    // Print tree rooted at current node using preorder traversal.
	public void printPreOrder( )
    {
        System.out.println( element );       // Node
        if( left != null )
            left.printPreOrder( );           // Left
        if( right != null )
            right.printPreOrder( );          // Right
    }


    // Print tree rooted at current node using postorder traversal.
	public void printPostOrder( )
    {
        if( left != null )
            left.printPostOrder( );          // Left
        if( right != null )
            right.printPostOrder( );         // Right
        System.out.println( element );       // Node
    }

    // Print tree rooted at current node using inorder traversal.
	public void printInOrder( )
    {
        if( left != null )
            left.printInOrder( );            // Left
        System.out.println( element );       // Node
        if( right != null )
            right.printInOrder( );           // Right
    }

	public BinaryNode<AnyType> duplicate( )
    {
        BinaryNode<AnyType> root = new BinaryNode<AnyType>( element, null, null );

        if( left != null )            // If there's a left subtree
            root.left = left.duplicate( );    // Duplicate; attach
        if( right != null )          // If there's a right subtree
            root.right = right.duplicate( );  // Duplicate; attach
        return root;                      // Return resulting tree
    }
    
	public AnyType getElement( )
    {
        return element;
    }
    
	public BinaryNode<AnyType> getLeft( )
    {
        return left;
    }
    

	public BinaryNode<AnyType> getRight( )
    {
        return right;
    }
    
	public void setElement( AnyType x )
    {
        element = x;
    }
    
	public void setLeft( BinaryNode<AnyType> t )
    {
        left = t;
    }
    
	public void setRight( BinaryNode<AnyType> t )
    {
        right = t;
    }

    private AnyType             element;
    private BinaryNode<AnyType> left;
    private BinaryNode<AnyType> right;
}

二叉树类实现

/**
 * BinaryTree class that illustrates the calling of
 * BinaryNode recursive routines and merge.
 */
public class BinaryTree<AnyType>
{
    public BinaryTree( )
    {
        root = null;
    }

    public BinaryTree( AnyType rootItem )
    {
        root = new BinaryNode<AnyType>( rootItem, null, null );
    }

    public void printPreOrder( )
    {
        if( root != null )
            root.printPreOrder( );
    }

    public void printInOrder( )
    {
        if( root != null )
           root.printInOrder( );
    }

    public void printPostOrder( )
    {
        if( root != null )
           root.printPostOrder( );
    }

    public void makeEmpty( )
    {
        root = null;
    }

    public boolean isEmpty( )
    {
        return root == null;
    }
    
    /**
     * Merge routine for BinaryTree class.
     * Forms a new tree from rootItem, t1 and t2.
     * Does not allow t1 and t2 to be the same.
     * Correctly handles other aliasing conditions.
     */
    public void merge( AnyType rootItem, BinaryTree<AnyType> t1, BinaryTree<AnyType> t2 )
    {
        if( t1.root == t2.root && t1.root != null )
        {
            System.err.println( "leftTree==rightTree; merge aborted" );
            return;
        }

            // Allocate new node
        root = new BinaryNode<AnyType>( rootItem, t1.root, t2.root );

            // Ensure that every node is in one tree
        if( this != t1 )
            t1.root = null;
        if( this != t2 )
            t2.root = null;
    }

    public int size( )
    {
        return BinaryNode.size( root );
    }

    public int height( )
    {
        return BinaryNode.height( root );
    }

    public BinaryNode<AnyType> getRoot( )
    {
        return root;
    }
    
    private BinaryNode<AnyType> root;

    static public void main( String [ ] args )
    {
        BinaryTree<Integer> t1 = new BinaryTree<Integer>( 1 );
        BinaryTree<Integer> t3 = new BinaryTree<Integer>( 3 );
        BinaryTree<Integer> t5 = new BinaryTree<Integer>( 5 );
        BinaryTree<Integer> t7 = new BinaryTree<Integer>( 7 );
        
        BinaryTree<Integer> t2 = new BinaryTree<Integer>( );
        BinaryTree<Integer> t4 = new BinaryTree<Integer>( );
        BinaryTree<Integer> t6 = new BinaryTree<Integer>( );

        t2.merge( 2, t1, t3 );
        t6.merge( 6, t5, t7 );
        t4.merge( 4, t2, t6 );

        System.out.println( "t4 should be perfect 1-7; t2 empty" );
        System.out.println( "----------------" );
        System.out.println( "t4" );
        t4.printInOrder( );
        System.out.println( "----------------" );
        System.out.println( "t2" );
        t2.printInOrder( );
        System.out.println( "----------------" );
        t4.size( ) ;
        t4.height( );
        System.out.println( "t4 size: " + t4.size( ) );
        System.out.println( "t4 height: " + t4.height( ) );
    }
}


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是用 C 语言实现的代码: ```c #include <stdio.h> #include <stdbool.h> #include <stdlib.h> /* 二叉树结点 */ struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; }; /* 队列结点 */ struct QueueNode { struct TreeNode* data; struct QueueNode* next; }; /* 队列 */ struct Queue { struct QueueNode* front; struct QueueNode* rear; }; /* 创建队列 */ struct Queue* createQueue() { struct Queue* queue = (struct Queue*)malloc(sizeof(struct Queue)); queue->front = queue->rear = NULL; return queue; } /* 判断队列是否为空 */ bool isQueueEmpty(struct Queue* queue) { return queue->front == NULL; } /* 入队 */ void enqueue(struct Queue* queue, struct TreeNode* data) { struct QueueNode* newNode = (struct QueueNode*)malloc(sizeof(struct QueueNode)); newNode->data = data; newNode->next = NULL; if (isQueueEmpty(queue)) { queue->front = queue->rear = newNode; } else { queue->rear->next = newNode; queue->rear = newNode; } } /* 出队 */ struct TreeNode* dequeue(struct Queue* queue) { if (isQueueEmpty(queue)) { return NULL; } else { struct TreeNode* data = queue->front->data; struct QueueNode* temp = queue->front; queue->front = queue->front->next; if (queue->front == NULL) { queue->rear = NULL; } free(temp); return data; } } /* 判断是否为完全二叉树 */ bool isCompleteTree(struct TreeNode* root) { if (root == NULL) { return true; } struct Queue* queue = createQueue(); enqueue(queue, root); bool flag = false; while (!isQueueEmpty(queue)) { struct TreeNode* temp = dequeue(queue); if (temp->left) { if (flag) { return false; } enqueue(queue, temp->left); } else { flag = true; } if (temp->right) { if (flag) { return false; } enqueue(queue, temp->right); } else { flag = true; } } return true; } /* 创建二叉树 */ struct TreeNode* createTree() { int val; scanf("%d", &val); if (val == -1) { return NULL; } struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val = val; root->left = createTree(); root->right = createTree(); return root; } /* 主函数 */ int main() { struct TreeNode* root = createTree(); if (isCompleteTree(root)) { printf("It is a complete binary tree.\n"); } else { printf("It is not a complete binary tree.\n"); } return 0; } ``` 原理: 完全二叉树(Complete Binary Tree)是指除了最后一层外,其他层的结点数都达到了最大值,最后一层的结点都集中在左侧。而对于一棵二叉树,如果它的层数为 h,那么它最多有 $2^h-1$ 个结点。因此,我们可以利用层序遍历的方式,对二叉树进行遍历,如果遇到某个结点缺少左子结点或右子结点,那么后续的结点必须全部为叶子结点,否则这棵二叉树就不是完全二叉树
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值