• 【算法leetcode】面试题 04.03. 特定深度节点链表(多语言实现)




    面试题 04.03. 特定深度节点链表:

    给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

    样例 1:

    输入:
    	[1,2,3,4,5,null,7,8]
    	
    	        1
    	       /  \ 
    	      2    3
    	     / \    \ 
    	    4   5    7
    	   /
    	  8
    
    输出:
    	[[1],[2,3],[4,5,7],[8]]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    分析

    • 面对这道算法题目,二当家的陷入了沉思。
    • 如果对二叉树和链表比较熟悉,就会明白其实就是二叉树的层序遍历,每一层组合成一条链表。

    题解

    rust

    // Definition for a binary tree node.
    // #[derive(Debug, PartialEq, Eq)]
    // pub struct TreeNode {
    //   pub val: i32,
    //   pub left: Option<Rc<RefCell<TreeNode>>>,
    //   pub right: Option<Rc<RefCell<TreeNode>>>,
    // }
    // 
    // impl TreeNode {
    //   #[inline]
    //   pub fn new(val: i32) -> Self {
    //     TreeNode {
    //       val,
    //       left: None,
    //       right: None
    //     }
    //   }
    // }
    // Definition for singly-linked list.
    // #[derive(PartialEq, Eq, Clone, Debug)]
    // pub struct ListNode {
    //   pub val: i32,
    //   pub next: Option<Box<ListNode>>
    // }
    // 
    // impl ListNode {
    //   #[inline]
    //   fn new(val: i32) -> Self {
    //     ListNode {
    //       next: None,
    //       val
    //     }
    //   }
    // }
    use std::rc::Rc;
    use std::cell::RefCell;
    impl Solution {
        pub fn list_of_depth(tree: Option<Rc<RefCell<TreeNode>>>) -> Vec<Option<Box<ListNode>>> {
            let mut ans: Vec<Option<Box<ListNode>>> = Vec::new();
    
            let mut queue = std::collections::VecDeque::new();
            queue.push_back(tree);
    
            while !queue.is_empty() {
                let mut head = Some(Box::new(ListNode::new(0)));
                let mut tail = head.as_mut();
                let size = queue.len();
                for _ in 0..size {
                    let node = queue.pop_front().unwrap().unwrap();
                    let mut node = node.borrow_mut();
                    if node.left.is_some() {
                        queue.push_back(node.left.take());
                    }
                    if node.right.is_some() {
                        queue.push_back(node.right.take());
                    }
                    tail.as_mut().unwrap().next = Some(Box::new(ListNode::new(node.val)));
                    tail = tail.unwrap().next.as_mut();
                }
                ans.push(head.as_mut().unwrap().next.take());
            }
    
            ans
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65

    go

    /**
     * Definition for a binary tree node.
     * type TreeNode struct {
     *     Val int
     *     Left *TreeNode
     *     Right *TreeNode
     * }
     */
    /**
     * Definition for singly-linked list.
     * type ListNode struct {
     *     Val int
     *     Next *ListNode
     * }
     */
    func listOfDepth(tree *TreeNode) []*ListNode {
        var ans []*ListNode
    	queue := []*TreeNode{tree}
    
    	for len(queue) > 0 {
    		head := &ListNode{}
    		tail := head
    		size := len(queue)
    		for i := 0; i < size; i++ {
    			node := queue[i]
    			if node.Left != nil {
    				queue = append(queue, node.Left)
    			}
    			if node.Right != nil {
    				queue = append(queue, node.Right)
    			}
    			tail.Next = &ListNode{Val: node.Val}
    			tail = tail.Next
    		}
    		ans = append(ans, head.Next)
    		queue = queue[size:]
    	}
    
    	return ans
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    typescript

    /**
     * Definition for a binary tree node.
     * class TreeNode {
     *     val: number
     *     left: TreeNode | null
     *     right: TreeNode | null
     *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.left = (left===undefined ? null : left)
     *         this.right = (right===undefined ? null : right)
     *     }
     * }
     */
    
    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     val: number
     *     next: ListNode | null
     *     constructor(val?: number, next?: ListNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.next = (next===undefined ? null : next)
     *     }
     * }
     */
    
    function listOfDepth(tree: TreeNode | null): Array<ListNode | null> {
        const ans = [];
    
    	const queue = [tree];
    
    	while (queue.length > 0) {
    		const head = new ListNode();
    		let tail = head;
    		const size = queue.length;
    		for (let i = 0; i < size; ++i) {
    			const { val, left, right } = queue.shift();
    			left && queue.push(left);
    			right && queue.push(right);
    			tail.next = new ListNode(val);
    			tail = tail.next;
    		}
    		ans.push(head.next);
    	}
    
    	return ans;
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    python

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def listOfDepth(self, tree: TreeNode) -> List[ListNode]:
            ans = []
            q = collections.deque()
            q.append(tree)
            while len(q) > 0:
                head = ListNode()
                tail = head
                size = len(q)
                for _ in range(size):
                    node = q.popleft()
                    node.left and q.append(node.left)
                    node.right and q.append(node.right)
                    tail.next = ListNode(node.val)
                    tail = tail.next
                ans.append(head.next)
            return ans
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    c

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    
    int getDepth(struct TreeNode* tree) {
        if (!tree) {
            return 0;
        }
        int leftDepth = getDepth(tree->left);
        int rightDepth = getDepth(tree->right);
        return fmax(leftDepth, rightDepth) + 1;
    }
    
    /**
     * Note: The returned array must be malloced, assume caller calls free().
     */
    struct ListNode** listOfDepth(struct TreeNode* tree, int* returnSize){
        int depth = getDepth(tree);
        struct ListNode **ans = malloc(depth * sizeof(struct ListNode *));
        *returnSize = 0;
        struct TreeNode *queue[(int) pow(2, depth) - 1];
        queue[0] = tree;
        int start = 0;
        int end = 1;
        while (start < end) {
            struct ListNode head = {};
            struct ListNode *tail = &head;
            int curEnd = end;
            while (start < curEnd) {
                struct TreeNode *node = queue[start++];
                if (node->left) {
                    queue[end++] = node->left;
                }
                if (node->right) {
                    queue[end++] = node->right;
                }
                tail->next = malloc(sizeof(struct ListNode));
                tail->next->val = node->val;
                tail->next->next = NULL;
                tail = tail->next;
            }
            ans[(*returnSize)++] = head.next;
        }
    
        return ans;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58

    c++

    /**
     * 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) {
            vector<ListNode *> ans;
    
            queue<TreeNode *> q;
            q.push(tree);
    
            while (q.size() > 0) {
                ListNode head = ListNode(0);
                ListNode *tail = &head;
                int size = q.size();
                for (int i = 0; i < size; ++i) {
                    TreeNode *node = q.front();
                    q.pop();
                    if (node->left != NULL) {
                        q.push(node->left);
                    }
                    if (node->right != NULL) {
                        q.push(node->right);
                    }
                    tail->next = new ListNode(node->val);
                    tail = tail->next;
                }
                ans.emplace_back(head.next);
            }
    
            return ans;
        }
    };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47

    java

    /**
     * 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) {
            List<ListNode> list = new ArrayList<>();
    
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(tree);
    
            while (!queue.isEmpty()) {
                ListNode head = new ListNode();
                ListNode tail = head;
                int      size = queue.size();
                for (int i = 0; i < size; ++i) {
                    TreeNode node = queue.poll();
                    if (node.left != null) {
                        queue.add(node.left);
                    }
                    if (node.right != null) {
                        queue.add(node.right);
                    }
                    tail.next = new ListNode(node.val);
                    tail = tail.next;
                }
                list.add(head.next);
            }
    
            ListNode[] ans = new ListNode[list.size()];
            list.toArray(ans);
    
            return ans;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48

    原题传送门:https://leetcode.cn/problems/list-of-depth-lcci/submissions/


    非常感谢你阅读本文~
    欢迎【点赞】【收藏】【评论】~
    放弃不难,但坚持一定很酷~
    希望我们大家都能每天进步一点点~
    本文由 二当家的白帽子:https://le-yi.blog.csdn.net/ 博客原创~


  • 相关阅读:
    Educational Codeforces Round 162(div2)||ABC
    怎样搭建Vue3项目
    AcWing 4604. 集合询问
    JavaEE进阶 - Spring Boot 配置文件 - 细节狂魔
    计算机图形学-算法总结
    Linux忘记密码
    【网络编程】套接字编程——TCP通信
    联想集团:长期前景稳定,业务转型正在提高盈利能力
    Tomcat深入浅出——最终章(六)
    springboot集成 生成二维码微信支付
  • 原文地址:https://blog.csdn.net/leyi520/article/details/125407346