114. 二叉树展开为链表
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
寻找前驱节点
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public void flatten(TreeNode root) {
while(root!=null){
if(root.left!=null){
TreeNode tnode = root.left;
while(tnode.right!=null){
tnode = tnode.right;
}
tnode.right = root.right;
root.right = root.left;
root.left = null;
}
root = root.right;
}
}
}
右左根来遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode last = null;
public void flatten(TreeNode root) {
if(root==null){
return;
}
flatten(root.right);
flatten(root.left);
root.right = last;
root.left = null;
last = root;
}
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
本文详细介绍了如何将二叉树原地转化为单链表的两种方法:通过寻找前驱节点和采用右左根遍历策略。文章提供了具体的算法实现代码,并引用了力扣(LeetCode)的题目链接。
928

被折叠的 条评论
为什么被折叠?



