为二叉树题目写测试用例

3,149 阅读2分钟

在做关于二叉树题目的时候想要验证自己写的程序是否是想要的结果时,需要写测试用例,但通常题目给我们的是数组,那么就需要将数组先转换成二叉树,然后将二叉树逐行或者按某种方式打印出来。

例如: LeetCode上第105题:

空节点如何打印出来呢?

思路: 首先将数组转换成二叉树,利用下面的arrayToTree()方法,然后利用层次遍历的思想,将数组转换成二叉树的结点依次进队,其中空节点也进队,只是给空结点传一个-1值,并且出队时判断这个结点是否是空结点,若是,则打印“null”,否则打印其val值。

Java

package nowcoder;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author LiuZhiguo
 * @date 2019/12/18 21:09
 */
public class PrintTreeLayer {
    <!--利用层次遍历的思想,将数组转换成二叉树的结点依次进队,其中空节点
    也进队,只是给空结点传一个-1值,并且出队时判断这个结点是否是空结点,
    若是,则打印“null”,否则打印其val值。-->
    public void printTreeLayer(TreeNode root){
        int depth = getDepth(root);
        if (root==null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        //根结点进队
        queue.offer(root);
        int currentDepth = 0;//用来记录出队结点所在层
        int count = 0;
        int beforeCount = 1;
        TreeNode p = new TreeNode(-1); //空结点时,进队
        while (!queue.isEmpty()) {
            TreeNode out = queue.poll();
            if (out.val == -1)
                System.out.print("null"+" ");
            else
                System.out.print(out.val+" ");
            count++;//记录这一层出队的个数
            if (out.left != null)
                queue.add(out.left);
            else if (currentDepth < depth-1)
                queue.offer(p);
            if (out.right != null)
                queue.add(out.right);
            else if (currentDepth < depth-1)
                queue.offer(p);
            if (count == beforeCount) {
                beforeCount = queue.size();//统计这一层的结点个数
                currentDepth ++;
                count =0;//清0,重新计数
            }
        }
    }
    //将数组转换成二叉树,并返回根结点
    TreeNode arrayToTree(Integer[] array, int index){
        TreeNode root = null;
        if (index < array.length) {
            Integer value = array[index];
            if (value == null) {
                return null;
            }
            root = new TreeNode(value);
            root.left = arrayToTree(array, 2*index+1);
            root.right = arrayToTree(array, 2*index+2);
            return root;
        }
        return root;
    }
    //得到树的深度
    private int getDepth(TreeNode root){
        if (root == null) return 0;
        int ld = getDepth(root.left);
        int rd = getDepth(root.right);
        return ld>rd?(ld+1):(rd+1);
    }
    public static void main(String[] args){
        PrintTreeLayer print = new PrintTreeLayer();
        Integer[] arr = {3, 9, 20, null, null, 15, 7};
        TreeNode root = print.arrayToTree(arr,0);
        print.printTreeLayer(root);
    }
}

结果:

3 9 20 null null 15 7 
Process finished with exit code 0

Python

import queue
class TreeNode:
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None
class PrintTreeLayer:
    def printTreeLayer(self, root):
        depth = self.getDepth(root)
        que = queue.Queue()
        if root is None:
            return None
        que.put(root)
        count = 0
        currentDepth = 0
        beforeCount = 1
        p = TreeNode(-1)
        while que.qsize() > 0:
            out = que.get()
            count += 1
            if out.val == -1:
                print("null", end=" ")
            else:
                print(out.val, end=" ")
            if out.left:
                que.put(out.left)
            elif currentDepth < depth-1:
                que.put(p)
            if out.right:
                que.put(out.right)
            elif currentDepth < depth-1:
                que.put(p)
            if count == beforeCount:
                beforeCount = que.qsize()
                currentDepth += 1
                count = 0


    def arrayToTree(self, array, index):
        root = None
        if index < len(array):
            value = array[index]
            if value is None:
                return None
            root = TreeNode(value)
            root.left = self.arrayToTree(array, index*2+1)
            root.right = self.arrayToTree(array, index*2+2)
            return root
        return root
    def getDepth(self,root):
        if root is None:
            return 0
        ld = self.getDepth(root.left)
        rd = self.getDepth(root.right)
        return max(ld, rd)+1
if __name__ == '__main__':
    test = PrintTreeLayer()
    array = [3, 9, 20, None, None, 15, 7]
    root = test.arrayToTree(array, 0) #转换成了一棵二叉树
    test.printTreeLayer(root)