原题链接:114. Flatten Binary Tree to Linked List
【思路】
当节点的左子树不为空时,将左子树放在节点的右边,并将节点的左边置为空,将右子树放在左子树的最右边。依次向右边遍历。
public class Solution {
public void flatten(TreeNode root) {
TreeNode p = root;
while (p != null) {
if(p.left != null) {
TreeNode left = p.left;
while(left.right != null) left = left.right;
left.right = p.right;
p.right = p.left;
p.left = null;
}
p = p.right;
}
}
}
225 / 225
test cases passed Runtime: 1 ms Your runtime beats 29.33% of javasubmissions.