美文网首页
2021-05-17打卡

2021-05-17打卡

作者: 程博颖 | 来源:发表于2021-05-17 10:04 被阅读0次
    image.png
    image.png
    public class ListOfDepth {
    
        public static class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
    
            TreeNode(int x) {
                val = x;
            }
        }
    
        public static class ListNode {
            int val;
            ListNode next;
    
            ListNode(int x) {
                val = x;
            }
        }
        public ListNode[] listOfDepth(TreeNode tree) {
            //递归计算出树的深度
            int depth = getDepth(tree);
            //初始化保存路径数组
           ListNode[] listNodes = new ListNode[depth];
            //采用队列临时存放树上每一层的节点
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(tree);
            int index = 0;
            //循环终止条件:树的最大深度
            while (!queue.isEmpty()) {
                int size = queue.size();
                ListNode newhead = new ListNode(0);
                ListNode indexNode = newhead;
                for (int i = 0; i < size; i++) {
                    TreeNode poll = queue.poll();
                    indexNode.next = new ListNode(poll.val);
                    indexNode = indexNode.next;
                    if (poll.left != null) {
                        queue.offer(poll.left);
                    }
                    if (poll.right != null) {
                        queue.offer(poll.right);
                    }
                }
                listNodes[index++] = newhead.next;
            }
            return listNodes;
        }
        private int getDepth(TreeNode treeNode) {
            if (treeNode == null) {
                return 0;
            }
            return Math.max(getDepth(treeNode.left), getDepth(treeNode.right)) + 1;
        }
    }
    

    相关文章

      网友评论

          本文标题:2021-05-17打卡

          本文链接:https://www.haomeiwen.com/subject/readjltx.html