public static void levelPrint(Node head) {
System.out.println("LevelPrint");
Node current;
Queue<Node> queue = new LinkedList<Node>();
Stack<Node> stack = new Stack<Node>();//和stack相关的全是获取最右节点
queue.add(head);
stack.add(head);
System.out.print(stack.peek().value + " ");
int start = 0;
int end = 1;
while(!queue.isEmpty()) {
current = queue.poll();
start++;
stack.add(current);
if(current.left != null) {
queue.add(current.left);
stack.add(current.left);
}
if(current.right != null) {
queue.add(current.right);
stack.add(current.right);
}
if(start == end && !queue.isEmpty()) {
start = 0;
end = queue.size();
System.out.print(stack.peek().value + " ");
}
}
}
二叉树获取每层的最右一个节点(二叉树的右视图)
最新推荐文章于 2023-10-12 15:15:58 发布