56 lines
1.6 KiB
Java
56 lines
1.6 KiB
Java
|
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;
|
|||
|
}
|
|||
|
}
|