摘要:复杂度思路设置一个指向下一层要遍历的节点的开头的位置。
LeetCode[117] Population Next Right Pointers in Each Node II
1 / 2 3 / 4 5 7 After calling your function, the tree should look like: 1 -> NULL / 2 -> 3 -> NULL / 4-> 5 -> 7 -> NULLIteration
复杂度
O(N),O(1)
思路
设置一个dummy node 指向下一层要遍历的节点的开头的位置。
代码
public void connect(TreeLinkNode root) { TreeLinkNode dummy = new TreeLinkNode(0); TreeLinkNode pre = dummy; while(root != null) { if(root.left != null) { pre.next = root.left; pre = pre.next; } if(root.right != null) { pre.next = root.right; pre = pre.next; } root = root.next; // done with the search of current level if(root == null) { root = dummy.next; pre = dummy; dummy.next = null; } } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/65292.html
摘要:题目要求给一个完全二叉树,将当前节点的值指向其右边的节点。而在中则是提供了一个不完全的二叉树,其它需求没有发生改变。我们需要使用一个变量来存储父节点,再使用一个变量来存储当前操作行的,将前一个指针指向当前父节点的子节点。 题目要求 Given a binary tree struct TreeLinkNode { TreeLinkNode *left; ...
题目:Follow up for problem Populating Next Right Pointers in Each Node. What if the given tree could be any binary tree? Would your previous solution still work? Note: You may only use constant extra sp...
摘要:原题链接广度优先搜索复杂度时间空间思路相当于是遍历二叉树。代码记录本层节点的个数最后一个节点的是,不做处理递归法复杂度时间空间递归栈空间思路由于父节点多了指针,我们不用记录父节点的父节点就能直到它相邻的节点。 Populating Next Right Pointers in Each Node I Given a binary tree struct TreeLinkNode { ...
Problem Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list. Lets take the foll...
Problem According to the Wikipedias article: The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970. Given a board with m ...
阅读 3521·2021-11-22 15:22
阅读 3313·2019-08-30 15:54
阅读 2701·2019-08-30 15:53
阅读 755·2019-08-29 11:22
阅读 3502·2019-08-29 11:14
阅读 2037·2019-08-26 13:46
阅读 2189·2019-08-26 13:24
阅读 2254·2019-08-26 12:22