一、问题描述
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
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
二、问题分析
mark:参照了网上代码。
三、算法代码
/**
* 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) {
if(root == null){
return;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
TreeNode p = null;
while(!stack.empty()){
p = stack.peek();
stack.pop();
if(p.right != null){
stack.push(p.right);
}
if(p.left != null){
stack.push(p.left);
}
p.left = null;
if (!stack.empty())
p.right = stack.peek();
}
}
}