【LeetCode】Flatten Binary Tree to Linked List
題目:Flatten Binary Tree to Linked List
<span style="font-size:18px;">/**LeetCode Flatten Binary Tree to Linked List
* 題意:給定一個二叉樹,將其轉變為一個相當於單連結串列的結構,觀察可知該結構即:每一個節點左兒子為空,右兒子指向自己先序遍歷時的下一個節點
* 思路:有觀察可得,應對其進行先序遍歷,得到正確的序列連線起來
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
package javaTrain;
public class Train18 {
public void flatten(TreeNode root) {
if(root== null || (root.left == null && root.right == null)) return;
preOrder(root);
return;
}
private TreeNode preOrder(TreeNode root){
if(root== null || (root.left == null && root.right == null)) return root;
TreeNode left = root.left;
TreeNode right = root.right;
TreeNode last;
root.left = null;
if(left != null){
root.right = left;
last = preOrder(left);
last.left = null;
if(right != null){
last.right = right;
return preOrder(right);
}
else return last;
}
else{
root.right = right;
return preOrder(right);
}
}
}
</span>
相關文章
- Leetcode Flatten Binary Tree to Linked ListLeetCode
- Leetcode-Flatten Binary Tree to Linked ListLeetCode
- Flatten Binary Tree to Linked List leetcode javaLeetCodeJava
- 【LeetCode從零單排】No 114 Flatten Binary Tree to Linked ListLeetCode
- [LeetCode] 430. Flatten a Multilevel Doubly Linked ListLeetCode
- [LeetCode] 1367. Linked List in Binary Tree 二叉樹中的連結串列LeetCode二叉樹
- 【LeetCode】Convert Sorted List to Binary Search TreeLeetCode
- Leetcode Convert Sorted List to Binary Search TreeLeetCode
- Convert Sorted List to Binary Search Tree leetcode javaLeetCodeJava
- LeetCode-Flatten Nested List IteratorLeetCode
- 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 Reverse Linked List IILeetCode
- Leetcode Linked List Cycle IILeetCode
- LeetCode Delete Node in a Linked ListLeetCodedelete
- Leetcode Palindrome Linked ListLeetCode
- LeetCode-Binary Tree PathsLeetCode
- leetcode - Binary Tree Preorder TraversalLeetCode
- Leetcode Binary Tree Inorder TraversalLeetCode
- Leetcode Binary Tree Preorder TraversalLeetCode
- Leetcode Binary Tree Postorder TraversalLeetCode
- Leetcode Maximum Depth of Binary TreeLeetCode
- Leetcode-Balanced Binary TreeLeetCode
- Balanced Binary Tree leetcode javaLeetCodeJava
- [leetcode]linked-list-cycle-iiLeetCode
- LeetCode 382 Linked List Random NodeLeetCoderandom
- LeetCode-Palindrome Linked ListLeetCode
- LeetCode-Linked List Random NodeLeetCoderandom
- LeetCode-Odd Even Linked ListLeetCode
- Leetcode-Reverse Linked List IILeetCode
- Leetcode-Linked List Cycle IILeetCode
- leetcode刷題--Reverse Linked ListLeetCode
- Reverse Linked List II leetcode javaLeetCodeJava