【LeetCode從零單排】No 114 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
解題思路:利用遞迴找到倒數第一個父節點,記錄下它的右節點,將左邊的移到右邊,然後再把之前標記的右節點連線上。
程式碼
public class Solution {
public void flatten(TreeNode root) {
if(root==null) return;
flatten(root.left);
flatten(root.right);
TreeNode temp=root.right;
if(root.left!=null){
root.right=root.left;
root.left=null;
while(root.right != null){
root=root.right;
}
root.right=temp;
}
}
}
/********************************
* 本文來自部落格 “李博Garvin“
* 轉載請標明出處:http://blog.csdn.net/buptgshengod
******************************************/
相關文章
- 【LeetCode】Flatten Binary Tree to Linked ListLeetCode
- Leetcode Flatten Binary Tree to Linked ListLeetCode
- Leetcode-Flatten Binary Tree to Linked ListLeetCode
- Flatten Binary Tree to Linked List leetcode javaLeetCodeJava
- 【LeetCode從零單排】No104 Maximum Depth of Binary TreeLeetCode
- 【LeetCode從零單排】No102 Binary Tree Level Order TraversalLeetCode
- [LeetCode] 430. Flatten a Multilevel Doubly Linked ListLeetCode
- 【LeetCode從零單排】No.160 Intersection of Two Linked ListsLeetCode
- 【LeetCode從零單排】No96 Unique Binary Search TreesLeetCode
- 【LeetCode從零單排】No83 Remove Duplicates from Sorted ListLeetCodeREM
- [LeetCode] 1367. Linked List in Binary Tree 二叉樹中的連結串列LeetCode二叉樹
- 【LeetCode】Convert Sorted List to Binary Search TreeLeetCode
- Leetcode Convert Sorted List to Binary Search TreeLeetCode
- 【LeetCode從零單排】No100 Same Tree && No101 Symmetric TreeLeetCode
- Convert Sorted List to Binary Search Tree leetcode javaLeetCodeJava
- LeetCode-Flatten Nested List IteratorLeetCode
- 【LeetCode從零單排】No38.CountAndSayLeetCode
- 【LeetCode從零單排】No.7 Reverse IntegerLeetCode
- 【LeetCode從零單排】No20.ValidParenthesesLeetCode
- 【LeetCode從零單排】No19.RemoveNthNodeFromEndofListLeetCodeREM
- 【LeetCode從零單排】No21.MergeTwoSortedListsLeetCode
- 【LeetCode從零單排】No27.Remove ElementLeetCodeREM
- 【LeetCode從零單排】No28 Implement strStr()LeetCode
- 【LeetCode從零單排】No22.Generate ParenthesesLeetCode
- leetcode Linked List CycleLeetCode
- Java for LeetCode 109 Convert Sorted List to Binary Search TreeJavaLeetCode
- [LeetCode] 109. Convert Sorted List to Binary Search TreeLeetCode
- 【Leetcode】109. Convert Sorted List to Binary Search TreeLeetCode
- Leetcode Binary Tree PathsLeetCode
- LeetCode Invert Binary TreeLeetCode
- Leetcode Balanced Binary TreeLeetCode
- 【LeetCode從零單排】No58.Length of Last WordLeetCodeAST
- 【LeetCode從零單排】No67.AddBinaryLeetCode
- 【LeetCode從零單排】No70.ClimbingStairsLeetCodeAI
- 【LeetCode從零單排】No.9 Palindrome NumberLeetCode
- 【LeetCode從零單排】No14.LongestCommonPrefixLeetCode
- 【LeetCode從零單排】No36 Valid SudokuLeetCode
- 【LeetCode從零單排】No221.Maximal SquareLeetCode