Problem Description
Given a binary tree, flatten it to a linked list in-place.
[https://leetcode.com/problems/flatten-binary-tree-to-linked-list/]
思路
先序遍历,然后按个保存就行了。。。
左右不分真的不利于手写代码。。。要不是调试一下就是反的了。。。
Code
package q114;
import TreeNode.*;
import java.util.*;
public class Solution {
public void flatten(TreeNode root) {
Stack<TreeNode> s=new Stack<TreeNode>();
s.push(root);
TreeNode next=null;
while(!s.isEmpty()){
TreeNode tmp=s.pop();
if(tmp==null) continue;
else {
if(next==null) next=tmp;
else{
next.right=tmp;
next.left=null;
next=tmp;
}
}
s.push(tmp.right);
s.push(tmp.left);
}
}
}