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
將二叉樹轉爲線性鏈表 從其轉換結果看 是將二叉樹的先序遍歷結果串成了鏈表 所以 可以先對二叉樹進行先序遍歷 將其節點值存好 然後構建鏈表 代碼如下:
public class Solution {
List<Integer> res=new ArrayList<Integer>();
public void flatten(TreeNode root) {
if(root==null)return ;
preorder(root);
TreeNode tmp=root;
for(int i=1;i<res.size();i++){
TreeNode n=new TreeNode(res.get(i));
tmp.right=n;
tmp.left=null;
tmp=n;
}
}
public void preorder(TreeNode root){
if(root==null)return;
res.add(root.val);
preorder(root.left);
preorder(root.right);
}
}
另外也可以直接進行 轉換 每次都將左邊所有的節點放到右邊 再將原右邊的所有節點放到原左邊的最後一個右節點處 代碼如下:
public class Solution {
public void flatten(TreeNode root) {
if(root==null) return ;
while(root!=null){
TreeNode tmp=root.right;
root.right=root.left;
root.left=null;
TreeNode p=root;
while(p.right!=null){
p=p.right;
}
p.right=tmp;
root=root.right;
}
}
}