题目原文:
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
题目大意:
把一个二叉树平铺到右子树上。
题目分析:
先递归平铺左右子树,再把左子树接到根节点右孩子上即可。
源码:(language:java)
/**
* 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;
}
flatten(root.left);
flatten(root.right);
TreeNode ptr = root.left;
if(ptr!=null){
while(ptr.right!=null){
ptr = ptr.right;
}
ptr.right = root.right;
root.right = root.left;
root.left = null;
}
}
}
成绩:
1ms,beats 34.42%,众数1ms,65.58%