摘要:復雜度思路設置一個指向下一層要遍歷的節(jié)點的開頭的位置。
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 指向下一層要遍歷的節(jié)點的開頭的位置。
代碼
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; } } }
文章版權歸作者所有,未經(jīng)允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65292.html
摘要:題目要求給一個完全二叉樹,將當前節(jié)點的值指向其右邊的節(jié)點。而在中則是提供了一個不完全的二叉樹,其它需求沒有發(fā)生改變。我們需要使用一個變量來存儲父節(jié)點,再使用一個變量來存儲當前操作行的,將前一個指針指向當前父節(jié)點的子節(jié)點。 題目要求 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...
摘要:原題鏈接廣度優(yōu)先搜索復雜度時間空間思路相當于是遍歷二叉樹。代碼記錄本層節(jié)點的個數(shù)最后一個節(jié)點的是,不做處理遞歸法復雜度時間空間遞歸棧空間思路由于父節(jié)點多了指針,我們不用記錄父節(jié)點的父節(jié)點就能直到它相鄰的節(jié)點。 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 ...
閱讀 3538·2021-11-22 15:22
閱讀 3328·2019-08-30 15:54
閱讀 2724·2019-08-30 15:53
閱讀 783·2019-08-29 11:22
閱讀 3529·2019-08-29 11:14
閱讀 2073·2019-08-26 13:46
閱讀 2210·2019-08-26 13:24
閱讀 2277·2019-08-26 12:22