leetcode-cn Daily Challenge on September 28th, 2020.
leetcode Daily Challenge on December 6th, 2020.
Difficulty : Medium
Related Topics : Tree、DFS
Given a binary tree
struct Node { int val; Node *left; Node *right; Node *next; }
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to
NULL
.Initially, all next pointers are set to
NULL
.
- You may only use constant extra space.
- Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
- The number of nodes in the given tree is less than
6000
.-100 <= node.val <= 100
- mine
- Java
Runtime: 1 ms, faster than 59.89%, Memory Usage: 38.9 MB, less than 90.79% of Java online submissions
// O(N)time // O(D)space Map<Integer, Node> map = new HashMap<>(); public Node connect(Node root) { helper(root, 0); return root; } void helper(Node node, int deepth){ if(node == null) return; if(map.containsKey(deepth)){ map.get(deepth).next = node; } map.put(deepth, node); helper(node.left, deepth + 1); helper(node.right, deepth + 1); }
- Java
- the most votes
Runtime: 0 ms, faster than 100.00%, Memory Usage: 38.6 MB, less than 99.34% of Java online submissions
// O(N)time // O(1)space public Node connect(Node root) { Node head = null; //head of the next level Node prev = null; //the leading node on the next level Node cur = root; //current node of current level while (cur != null) { while (cur != null) { //iterate on the current level //left child if (cur.left != null) { if (prev != null) { prev.next = cur.left; } else { head = cur.left; } prev = cur.left; } //right child if (cur.right != null) { if (prev != null) { prev.next = cur.right; } else { head = cur.right; } prev = cur.right; } //move to next node cur = cur.next; } //move to next level cur = head; head = null; prev = null; } return root; }