[Leetcode] Flatten Binary Tree to Linked List 整平二叉树
生活随笔
收集整理的這篇文章主要介紹了
[Leetcode] Flatten Binary Tree to Linked List 整平二叉树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Flatten Binary Tree to Linked List
Given a binary tree, flatten it to a linked list in-place.
For example, Given
1/ \2 5/ \ \3 4 6The flattened tree should look like:
1\2\3\4\5\6棧法
復雜度
時間 O(N) 空間 O(N)
思路
對于一個根節點,我們將它的右子樹壓進一個棧中,然后將它的左子樹放到右邊來。如果該節點沒有左子樹,說明該節點是某個左子樹的最后一個節點,我們這時候把棧中最近的右子樹pop出來接到它的右邊。
代碼
public class Solution {public void flatten(TreeNode root) {Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode p = root;while(p != null || !stack.empty()){// 如果有右子樹,先壓入棧,等待遇到當前節點左子樹盡頭的時候再pop出來if(p.right != null){stack.push(p.right);}// 如果存在左子樹,將它放到右邊來if(p.left != null){p.right = p.left;p.left = null;// 否則,說明是某個左子樹的盡頭,就將最近的右子樹接到右邊來}else if(!stack.empty()){TreeNode temp = stack.pop();p.right=temp;}// 移動到下一個待flat節點p = p.right;}} }2018/2
class Solution:def flatten(self, root):""":type root: TreeNode:rtype: void Do not return anything, modify root in-place instead."""stack = []currentNode = rootwhile currentNode is not None:if currentNode.right is not None:stack.append(currentNode.right)if currentNode.left is not None:currentNode.right = currentNode.leftcurrentNode.left = Noneelif stack:currentNode.right = stack.pop()currentNode = currentNode.right2018/10
func flatten(root *TreeNode) {if root == nil {return}stack := []*TreeNode{root}curr := &TreeNode{0, nil, nil}for len(stack) != 0 {top := stack[len(stack)-1]stack = stack[:len(stack)-1]// DFS from left to right, push right to the stack firstif top.Right != nil {stack = append(stack, top.Right)}// push left to the stackif top.Left != nil {stack = append(stack, top.Left)}// put top to curr's right and clear curr's leftcurr.Left = nilcurr.Right = top// move on to the nextcurr = curr.Right} }鏈接左右子樹法
復雜度
時間 O(N) 空間 O(1)
思路
如果我們將根節點的右子樹接到左子樹最后一個節點(就是左子樹盡可能靠右下的節點)的右邊,那我們可以確定的是,該根節點是已經flat的了。執行完該鏈接操作,根節點就只有右子樹了,這樣我們再移動到右子樹的根節點,反復執行同樣的操作,每次保證一個節點被flat。
代碼
public class Solution {public void flatten(TreeNode root) {while(root != null){// 當存在左子樹時,說明該節點還沒被flatif(root.left != null){// 找到左子樹最后一個節點TreeNode endOfLeftSubTree = root.left;while(endOfLeftSubTree.right != null){endOfLeftSubTree = endOfLeftSubTree.right;}// 將右子樹加到左子樹最后一個節點的右邊endOfLeftSubTree.right = root.right;// 將左子樹放到當前節點的右邊root.right = root.left;// 將當前節點左邊置空root.left = null;}// 移動到下一個待flat的節點root = root.right;}} }總結
以上是生活随笔為你收集整理的[Leetcode] Flatten Binary Tree to Linked List 整平二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: lvs + keepalived HOW
- 下一篇: kitkat-s5p4418drone