【LeetCode 中等題】56-填充同一層的兄弟節點II
阿新 • • 發佈:2019-01-08
題目描述:給定一個二叉樹
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
填充它的每個 next 指標,讓這個指標指向其下一個右側節點。如果找不到下一個右側節點,則將 next 指標設定為 NULL
。
初始狀態下,所有 next 指標都被設定為 NULL
。
說明:
- 你只能使用額外常數空間。
- 使用遞迴解題也符合要求,本題中遞迴程式佔用的棧空間不算做額外的空間複雜度。
示例:
給定二叉樹,
1 / \ 2 3 / \ \ 4 5 7
呼叫你的函式後,該二叉樹變為:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
解法1。遞迴,對每個節點,先找到它的next節點的第一個非空子節點(非左即右),然後安排好自個的右節點指向(如果非空的話)、左節點指向,然後遞迴遍歷右子節點、左子節點,應該是得先把右邊處理好了,再找左邊吧,這個過程呈現先右後左的趨勢。
class Solution: # @param root, a tree link node # @return nothing def connect(self, root): if not root: return post = root.next while post: if post.left: post = post.left break if post.right: post = post.right break post = post.next if root.right: root.right.next = post if root.left: if root.right: root.left.next = root.right else: root.left.next = post self.connect(root.right) self.connect(root.left)
解法2。
# Definition for binary tree with next pointer. # class TreeLinkNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None class Solution: # @param root, a tree link node # @return nothing def connect(self, root): if not root: return dummy = TreeLinkNode(0) cur = dummy while root: if root.left: cur.next = root.left cur = cur.next if root.right: cur.next = root.right cur = cur.next root = root.next if not root: cur = dummy root = dummy.next dummy.next = None