leetcode 114.Flatten Binary Tree to Linked List (将二叉树转换链表) 解题思路和方法
2023-09-11 14:14:09 时间
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
思路:这题主要是就是前序遍历。主要解法就是将左子树转换为右支树,同一时候加入在右子树前。左子树求解时,须要主要左子树的深度。
详细代码例如以下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public void flatten(TreeNode root) { if(root == null){ return; } TreeNode r = new TreeNode(0); fun(root,r); root = r.right; } private boolean fun(TreeNode root, TreeNode t){ if(root == null){ return false; } TreeNode p = root.left; TreeNode q = root.right; t.right = root; t.left = null; if(p != null){ if(fun(p, t.right)){ if(q != null){ TreeNode k = t.right; while(k.right != null){ k = k.right; } fun(q,k); } }else{ if(q != null){ fun(q,t.right); } } }else{ if(q != null){ fun(q,t.right); } } return true; } }
相关文章
- Leetcode: Construct Binary Tree from Preorder and Inorder Traversal
- 【Leetcode】691. 贴纸拼词(困难)
- JS Leetcode 155. 最小栈 题解分析
- [LeetCode]5400. 旅行终点站
- LeetCode 54. 螺旋矩阵
- LeetCode | 循环队列的爱情【恋爱法则——环游世界】
- 113、【树与二叉树】leetcode ——538. 把二叉搜索树转换为累加树:递增数组视角右中左遍历(C++版本)
- 112、【树与二叉树】leetcode ——108. 将有序数组转换为二叉搜索树:二分查找树(C++版本)
- LeetCode 232: Implement Queue using Stacks
- [LeetCode] 1047. Remove All Adjacent Duplicates In String 移除字符串中所有相邻的重复字符
- [LeetCode] 1155. Number of Dice Rolls With Target Sum 掷骰子的N种方法
- [LeetCode] 1017. Convert to Base -2 负二进制转换
- [LeetCode] 977. Squares of a Sorted Array 有序数组的平方值
- [LeetCode] Course Schedule III 课程清单之三
- [LeetCode] Tenth Line 第十行
- LeetCode将有序数组转换为二叉搜索树