题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
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(int x) { val = x; }
* }
*/
class Solution {
public void flatten(TreeNode root) {
if (root == null || (root.left == null && root.right == null))
return;
flatten(root.left);
flatten(root.right);
//到这一步,root节点下面最多就只有俩节点
if (root.left != null){
TreeNode tmpRight = root.right;
root.right = root.left;
root.left = null;
TreeNode r = root.right;
while(r.right != null){
r = r.right;
}
r.right = tmpRight;
}
}
}
网友评论