Print binary tree in BFS fashion with O(1) space

前端 未结 4 808
礼貌的吻别
礼貌的吻别 2021-01-12 12:26

I was wondering if it\'s possible to print a binary tree in breadth first order while using only O(1) space?

The difficult part is that one have to use additional sp

4条回答
  •  暖寄归人
    2021-01-12 12:58

    It is easy to implement a recursive method to get all the nodes of a tree at a given level. Hence, we could calculate the height of the tree and get all the nodes and each level. This is Level Order Traversal of the tree. But, the time complexity is O(n^2). Below is the Java implementation (source).

    class Node 
    { 
        int data; 
        Node left, right; 
        public Node(int item) 
        { 
            data = item; 
            left = right = null; 
        } 
    } 
    
    class BinaryTree 
    { 
        Node root; 
    
        public BinaryTree() 
        { 
            root = null; 
        } 
    
        void PrintLevelOrder() 
        { 
            int h = height(root); 
            int i; 
            for (i=1; i<=h; i++) 
                printGivenLevel(root, i); 
        } 
    
        int Height(Node root) 
        { 
            if (root == null) 
               return 0; 
            else
            { 
                int lheight = height(root.left); 
                int rheight = height(root.right); 
    
            } 
        } 
    
        void PrintGivenLevel (Node root ,int level) 
        { 
            if (root == null) 
                return; 
            if (level == 1) 
                System.out.print(root.data + " "); 
            else if (level > 1) 
            { 
                printGivenLevel(root.left, level-1); 
                printGivenLevel(root.right, level-1); 
            } 
        }
    }
    

提交回复
热议问题