forked from chuyi2007/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFlattenBinaryTree.java
More file actions
35 lines (35 loc) · 966 Bytes
/
FlattenBinaryTree.java
File metadata and controls
35 lines (35 loc) · 966 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
//O(N)
public class Solution {
public void flatten(TreeNode root) {
// Start typing your Java solution below
// DO NOT write main() function
Stack<TreeNode> st = new Stack<TreeNode>();
st.push(root);
TreeNode cur = null;
while(!st.isEmpty() && st.peek() != null){
TreeNode parent = st.pop();
if(parent.right != null)
st.push(parent.right);
if(parent.left != null)
st.push(parent.left);
parent.right = null;
parent.left = null;
if(parent == root){
cur = parent;
}
else{
cur.right = parent;
cur = cur.right;
}
}
}
}