思路一:递归先序遍历
中左右,即把左放在右的位置,再把右接在左的下面
class Solution:def flatten(self, root: TreeNode) -> None:"""Do not return anything, modify root in-place instead."""if not root or (not root.left and not root.right):return self.flatten(root.left)self.flatten(root.right)tmp=root.rightroot.right=root.leftroot.left=Nonewhile(root.right):root=root.rightroot.right=tmp
class Solution {public void flatten(TreeNode root) {if(root==null || (root.left==null && root.right==null)){return;}flatten(root.left);flatten(root.right);TreeNode temp=root.right;root.right=root.left;root.left=null;while(root.right!=null){root=root.right;}root.right=temp;}
}
思路二:非递归
class Solution:def flatten(self, root: TreeNode) -> None:"""Do not return anything, modify root in-place instead."""stack=[]while root or stack:if root:stack.append(root)root=root.leftelse:node=stack.pop()tmp=node.rightroot=tmpnode.right=node.leftnode.left=Nonewhile node.right:node=node.rightnode.right=tmp
class Solution {public void flatten(TreeNode root) {List<TreeNode>stack&#61;new ArrayList<>();while(root!&#61;null || stack.size()!&#61;0){if(root!&#61;null){stack.add(root);root&#61;root.left;}else{TreeNode node&#61;stack.remove(stack.size()-1);TreeNode temp&#61;node.right;root&#61;temp;node.right&#61;node.left;node.left&#61;null;while(node.right!&#61;null){node&#61;node.right;}node.right&#61;temp;}}}
}