1 题目描述
给定一个二叉树的 根节点 root,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。116.填充每个节点的下一个右侧节点指针,117.填充每个节点的下一个右侧节点指针ll
2 解题思路
二叉树层序遍历的拓展:
思想:
1) 利用队列找出每一层的个数,即分界点;
2)特例法先写出为只有两层节点时的代码情况,再逐步推进。
3 代码
public Node connect(Node root) {
// 二叉树的拓展
if(root == null) return root;
Queue<Node> que = new LinkedList<>();
que.offer(root);
while(!que.isEmpty()){
int len = que.size();
Node cur = leRight(que);
// Node cur = que.poll();
// if(cur.left != null) que.offer(cur.left);
// if(cur.right != null) que.offer(cur.right);
while(len>1){
cur.next =que.poll();
cur = cur.next;
if(cur.left != null) que.offer(cur.left);
if(cur.right != null) que.offer(cur.right);
len--;
}
cur.next = null;
}
return root;
}
private Node leRight(Queue<Node> que){
Node cur = que.poll();
if(cur.left != null) que.offer(cur.left);
if(cur.right != null) que.offer(cur.right);
return cur;
}