HERE是不使用队列即可正确查看二叉树的C++实现。当我尝试将其转换为Java时,它不起作用。这是我的Java代码:

(我认为很可能是因为我没有正确理解算法以及对maxLevel指针/引用的处理)

public static void rightView(TreeNode tNode){
    int maxLevel = 0;
    rViewUtil(tNode, 1,maxLevel);
}

public static void rViewUtil(TreeNode tNode, int level, int maxLevel){
    if(tNode==null)
        return;
    if(maxLevel < level){
        System.out.print(tNode.value + " ");
        maxLevel = level;
    }
    rViewUtil(tNode.right, level+1, maxLevel);
    rViewUtil(tNode.left, level+1, maxLevel);
}

最佳答案

本着@lifus回答的精神,但避免了可变状态,您可以使用函数return设置maxLevel

public static void rightView(TreeNode tNode){
    int maxLevel = 0;
    rViewUtil(tNode, 1,maxLevel);
}

public static int rViewUtil(TreeNode tNode, int level, int maxLevel){
    if(tNode==null)
        return;
    if(maxLevel < level){
        System.out.print(tNode.value + " ");
        maxLevel = level;
    }
    maxLevel = rViewUtil(tNode.right, level+1, maxLevel);
    maxLevel = rViewUtil(tNode.left, level+1, maxLevel);
    return maxLevel
}

08-08 06:30