展平多向链表

 

一歪脑袋是二叉树,哈哈,其实我没发现,但是也是用递归,并不优雅的递归,后来受大佬的启发

/*
// Definition for a Node.
class Node {
    public int val;
    public Node prev;
    public Node next;
    public Node child;
};
*/

class Solution {
    Node t = new Node();
    public Node flatten(Node head) {
        if(head == null) return null;
        Node res = head;
        child(res);
        if(head != null){
            head.prev = null;
        }
        return head;
    }
    public void child(Node node){
        if(node == null){
            return ;
        }
        Node l = node.child;
        Node r = node.next;
        t.next = node;
        node.prev = t;
        t = node;
        node.child = null;
        child(l);
        child(r);
    }
}

使用先序遍历,正好借这个机会写一下二叉树的先序遍历、中序、后序

先序

protected void preorder(TreeNode<E> root) {

    if (root == null)
        return;

    System.out.println(root.element + " ");

    preorder(root.left);

    preorder(root.right);
}

中序

 

protected void inorder(TreeNode<E> root) {

    if (root == null)
        return;

    inorder(root.left);

    System.out.println(root.element + " ");

    inorder(root.right);
}

后序

protected void postorder(TreeNode<E> root) {

    if (root == null)
        return;

    postorder(root.left);

    postorder(root.right);

    System.out.println(root.element + " ");
}

 

posted @ 2021-08-26 14:18  K峰  Views(126)  Comments(0)    收藏  举报