N叉树与二叉树的相互转换
题目描述
将一颗N叉树转换成一颗二叉树,将一棵二叉树树还原成一棵N叉树
题目分析
N叉树转换成二叉树,可以将N叉树的子树全看成二叉树的左节点的右节点。每颗子树也是如此。
代码
public class EncodeNaryTreeToBinaryTree {
public static class Node {
public int val;
public List<Node> children;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, List<Node> _children) {
val = _val;
children = _children;
}
};
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Codec {
// Encodes an n-ary tree to a binary tree.
public TreeNode encode(Node root) {
if(root ==null){
return null;
}
TreeNode treeNode = new TreeNode(root.val);
treeNode.left = en(root.children);
return treeNode;
}
private TreeNode en(List<Node> root) {
TreeNode head = null;
TreeNode cur = null;
for (Node t: root) {
TreeNode tNode = new TreeNode(t.val);
if(head==null){
head = tNode;
}else{
cur.right = tNode;
}
cur= tNode;
cur.left = en(t.children);
}
return head;
}
// Decodes your binary tree to an n-ary tree.
public Node decode(TreeNode root) {
if(root ==null){
return null;
}
return new Node(root.val,de(root.left));
}
private List<Node> de(TreeNode root) {
List<Node> childs=new ArrayList<>();
while(root!=null){
Node node =new Node(root.val,de(root.left));
childs.add(node);
root = root.right;
}
return childs;
}
}
}
小结
- 这里编码涉及到的递归都是半递归,左子树用递归得到,右子树用迭代。
- 分析好递归的起始点,并不是整棵树进来就是递归,而是在建子树和左子树的时候进行递归。