Leecode specific depth node linked list

Original title

Given a binary tree, design an algorithm to create a linked list containing all nodes at a certain depth (for example, if the depth of a tree is D, then D linked lists will be created). Returns an array of linked lists of all depths.

Example:

输入:[1,2,3,4,5,null,7,8]

        1
       /  \ 
      2    3
     / \    \ 
    4   5    7
   /
  8

输出:[[1],[2,3],[4,5,7],[8]]
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<ListNode*> listOfDepth(TreeNode* tree) {
    
    

    }
};

Source: LeetCode
Link: https://leetcode-cn.com/problems/list-of-depth-lcci The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Problem-solving ideas

This question is not at all possible, but it does not matter, just learn and do it now.

  • The first step: mark keywords

Given a binary tree , design an algorithm to create a linked list containing all nodes at a certain depth (for example, if the depth of a tree is D, then D linked lists will be created). Returns an array of linked lists of all depths.

  • Step 2: Baidu is now learning

1.
What is a binary tree?
2. Detailed explanation of linked
list (easy to understand)

  • Step 3: Look at the answer

Even if you understand the basic concepts of binary trees and linked lists, you still won't be converted into algorithms, because you have never done it before, so just look at the answer and see how others do it.

Reference answer (1)

This mainly 二叉树的层序遍历, additional processing when the list was used dummysuch 虚拟节点,
that the code number is relatively simple, without 考虑headthe

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public ListNode[] listOfDepth(TreeNode tree) {
    
    
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(tree);

        List<ListNode> res = new ArrayList<>();
        ListNode dummy = new ListNode(0);
        while (!queue.isEmpty()) {
    
    
            int size = queue.size();
            ListNode curr = dummy;
            for (int i = 0; i < size; i++) {
    
    
                TreeNode treeNode = queue.poll();
                curr.next = new ListNode(treeNode.val);
                if (treeNode.left != null) {
    
    
                    queue.offer(treeNode.left);
                }
                if (treeNode.right != null) {
    
    
                    queue.offer(treeNode.right);
                }
                curr = curr.next;
            }
            res.add(dummy.next);
            dummy.next = null;
        }

        return res.toArray(new ListNode[] {
    
    });
    }
}

Author: fisher12
link: https: //leetcode-cn.com/problems/list-of-depth-lcci/solution/ceng-xu-bian-li-by-fisher12/
Source: stay button (LeetCode)
copyright reserved by the authors . For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

The difference between add/offer, remove/poll, element/peek in the LinkedList
binary tree java code creation

operation result:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 单链表
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

/**
 * 二叉树
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    

    public static ListNode[] listOfDepth(TreeNode tree) {
    
    
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(tree);
        List<ListNode> res = new ArrayList<ListNode>();
        ListNode dummy = new ListNode(0);

        while (!queue.isEmpty()) {
    
    
            int size = queue.size();
            ListNode curr = dummy;
            for (int i = 0; i < size; i++) {
    
    
                TreeNode treeNode = queue.poll();
                curr.next = new ListNode(treeNode.val);

                if (treeNode.left != null) {
    
    
                    queue.offer(treeNode.left);
                }
                if (treeNode.right != null) {
    
    
                    queue.offer(treeNode.right);
                }

                curr = curr.next;
            }

            res.add(dummy.next);
            dummy.next = null;
        }

        //最后把结果列表转换为数组返回
        //所以这个算法实际做的是把二叉树遍历,把值放到列表里再生成数组返回
        //核心在于遍历
        return res.toArray(new ListNode[] {
    
    });
    }

    public static void main(String[] args) {
    
    
        TreeNode tA = new TreeNode(1);
        TreeNode tB = new TreeNode(2);
        TreeNode tC = new TreeNode(3);
        TreeNode tD = new TreeNode(4);
        TreeNode tE = new TreeNode(5);
        TreeNode tF = new TreeNode(7);
        TreeNode tG = new TreeNode(8);

        /**
         *              A
         *          B         C
         *      D       E   F     G
         */
        tA.left = tB;
        tA.right = tC;

        tB.left= tD;
        tB.right = tE;

        tC.left =tF;
        tC.right = tG;

        //现在只要把tA放入算法,就能得出结果了。
        ListNode[] listNodes = listOfDepth(tA);
        for (ListNode listNode : listNodes) {
    
    
            int i = 1;
            ListNode curr = listNode;
            if (curr.next == null){
    
    
                System.out.print("--- "+listNode.val);
            }else {
    
    
                while (curr.next != null){
    
    
                    if (i == 1){
    
    
                        System.out.print("--- "+curr.val);
                        i = 0;
                    }else {
    
    
                        curr = curr.next;
                        System.out.print(" "+curr.val+" ");
                    }
                }
            }

            System.out.println("");

        }

    }
}

Expected output:

--- 1
--- 2 3 
--- 4 5  7  8 

Guess you like

Origin blog.csdn.net/weixin_42072754/article/details/109350422