Algorithm/src/main/java/tree/Connect.java

56 lines
1.6 KiB
Java
Raw Normal View History

2025-05-16 14:49:54 +08:00
package tree;
import java.util.LinkedList;
import java.util.Queue;
/**
* 题目 117. 填充每个节点的下一个右侧节点指针 II (buildTree)
* 描述给定两个整数数组 inorder postorder 其中 inorder 是二叉树的中序遍历 postorder 是同一棵树的后序遍历请你构造并返回这颗 二叉树
示例 2
输入inorder = [9,3,15,20,7], postorder = [9,15,7,20,3]
输出[3,9,20,null,null,15,7]
* 链接https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
*/
public class Connect {
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
public Node connect(Node root) {
Queue<Node>queue=new LinkedList<>();
if(root==null)return null;
queue.offer(root);
while (!queue.isEmpty()){
int sz=queue.size();
Node cur=queue.poll();
if(cur.left!=null)queue.offer(cur.left);
if(cur.right!=null)queue.offer(cur.right);
for (int i = 1; i < sz; i++) {
Node next =queue.poll();
cur.next=next;
cur=next;
if(cur.left!=null)queue.offer(cur.left);
if(cur.right!=null)queue.offer(cur.right);
}
}
return root;
}
}