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
Given a binary tree, flatten it to a linked list in-place.
题目很简单,就是将一棵树化成一棵右单支树,过程是:将节点的作节点接到右节点的位置,原来的右节点接到现在右节点(也就是左节点)的最右节点的右子树,重复这个过程,直到是一棵右单支树。
/**
* Definition for binary tree
* 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;
}
TreeNode p = root;
TreeNode left = null;
TreeNode right = null;
TreeNode q = null;
while(p != null ){//空节点退出
left = p.left;
right = p.right;
if(left != null){//左子树不空,需要知道左子树的最右节点
q = ButtomRight(left);
p.left = null;
p.right = left;
q.right = right;
p = p.right;
}else{//左子树为空
p = p.right;
}
}
}
public TreeNode ButtomRight(TreeNode root){//返回root的最右节点
TreeNode tmp = root;
while(root.right != null){
tmp = root.right;
root = root.right;
}
return tmp;
}
}Flatten Binary Tree to Linked List
原文:http://blog.csdn.net/havedream_one/article/details/44905591