您的位置:首页 > 其它

LeetCode Flatten Binary Tree to Linked List

2015-09-09 08:03 423 查看
原题链接在这里:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

Method 1: 前序遍历,都加到List里,最后从List加到树里。Time O(n), Space O(n).

Method 2: 在做Pre-order时更改树的结构,使用stack特性,每次出栈时加到lastVisit的右子点,同时更新lastVisit点。

Note: root是不加到任何点的右子点的,所以要加一个限定条件,建立lastVisited = null, 检查lastVisit不为空时才加出栈点到右子,否则跳过,之后才对lastVisited做第一次赋值。

AC Java:

/**
* 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) {
/*
//Method 1
List<Integer> ls = new ArrayList<Integer>();
preOrder(root,ls);
int size = ls.size();
TreeNode cur = root;
for(int i = 1; i<size; i++){
cur.left = null;
cur.right = new TreeNode(ls.get(i));
cur = cur.right;
}
}
private void preOrder(TreeNode root, List<Integer> ls){
if(root == null){
return;
}
ls.add(root.val);
if(root.left != null){
preOrder(root.left, ls);
}
if(root.right != null){
preOrder(root.right, ls);
}
}
*/

//Method 2
if(root == null){
return;
}
Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(root);
TreeNode lastVisited = null;
while(!stk.empty()){
TreeNode tn = stk.pop();
if(lastVisited != null){
lastVisited.left = null;
lastVisited.right = tn;
}
lastVisited = tn;
if(tn.right != null){
stk.push(tn.right);
}
if(tn.left != null){
stk.push(tn.left);
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: