【LeetCode】114.Flatten Binary Tree to Linked List(Medium)解题报告
题目地址:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/
题目描述:
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
Solution1:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
两种方法
time : O(n)
space : O(n)
*/
class Solution {
private TreeNode prev = null;
public void flatten(TreeNode root) {
if(root == null) return;
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
}
Solution2:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
两种方法
time : O(n)
space : O(n)
*/
class Solution {
private TreeNode prev = null;
public void flatten(TreeNode root) {
if(root == null) return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode cur = stack.pop();
if(cur.right != null) stack.push(cur.right);
if(cur.left != null) stack.push(cur.left);
if(!stack.isEmpty()){
cur.right = stack.peek();
}
cur.left = null;
}
}
}
Date:2018年4月7日