Total Accepted: 123537
Total Submissions: 357891
Difficulty: Medium
Contributor: LeetCode
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
这题是一个先序遍历的结果,但是注意的有两点
1. 在遍历构建过程中,需要把左子数置空;
2. 需要记录左子数中最后一个访问的节点
要求的方法是没有返回值的,所以我们要构建一个辅助方法来递归的构建,给出我的代码,1ms,O(1)空间复杂度
/**
* 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 last = expand(root);
}
TreeNode expand(TreeNode root){
if(root.left==null && root.right==null) return root;
TreeNode right = root.right;
TreeNode left = root.left;
if(left!=null){
root.right = left;
root.left = null;
root = expand(left);
}
if(right!=null){
root.right = right;
root = expand(root.right);
}
return root;
}
}