Counting nodes in a tree in Java

前端 未结 15 1762
我寻月下人不归
我寻月下人不归 2020-12-03 00:03

First of all, I swear this is not homework, it\'s a question I was asked in an interview. I think I made a mess of it (though I did realise the solution requires recursion).

15条回答
  •  难免孤独
    2020-12-03 00:26

    My first attempt didn't have anything new to add, but then I started to wonder about recursion depth and whether it would be possible to rearrange the code to take advantage of the tail call optimization feature of the latest Java compiler. The main problem was the null test - which can be solved using a NullObject. I'm not sure if TCO can deal with both recursive calls, but it should at least optimize the last one.

    static class NullNode extends Tree {
    
        private static final Tree s_instance = new NullNode();
    
        static Tree instance() {
            return s_instance;
        }
    
        @Override
        Tree getRightChild() {  
            return null;
        }  
    
        @Override
        Tree getLeftChild() {  
            return null;
        }  
    
        int count() {  
            return 0;
        }
    }
    
    int count() {      
        Tree right = getRightChild();      
        Tree left  = getLeftChild();      
    
        if ( right == null ) { right = NullNode.instance(); }
        if ( left  == null ) { left  = NullNode.instance(); }
    
        return 1 + right.count() + left.count();
    }   
    

    The precise implementation of NullNode depends on the implementations used in Tree - if Tree uses NullNode instead of null, then perhaps the child access methods should throw NullPointerException instead of returning null. Anyway, the main idea is to use a NullObject in order to try to benifit from TCO.

提交回复
热议问题