Flatten Binary Tree to Linked List (深度优先搜索)
翻转二叉树为链表
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
public void flatten(TreeNode root) {
if(root == null)return;
flattenSubTree(root);
}
private TreeNode flattenSubTree(TreeNode root){
if (root == null){
return null;
}else if (root.left == null && root.right == null){
return root;
}else{
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
if (left != null){
root.right = left;
TreeNode temp = flattenSubTree(left);
temp.left = null;
if (right != null){
temp.right = right;
}else{
return temp;
}
}
return flattenSubTree(right);
}
}
}