题目:给定一个二叉树,原地将它展开为链表。
例如,给定二叉树:
1
/ \
2 5
/ \ \
3 4 6
将其展开为:
1
\
2
\
3
\
4
\
5
\
6
思路:
将左子树插入到右子树的地方
将原来的右子树接到左子树的最右边节点
考虑新的右子树的根节点,一直重复上边的过程,直到新的右子树为 null
源码:GitHub源码
/**
* 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) {
while (root != null) {
if(root.left == null) root = root.right;
else{
TreeNode tmp = root.left;
while(tmp.right != null){
tmp = tmp.right;
}
tmp.right = root.right;
root.right = root.left;
root.left = null;
root = root.right;
}
}
}
}