给定一棵二叉树,把它转化为一棵扁平的二叉树。如下面左边的二叉树,扁平化后的结果为右边的二叉树。
方法一:利用递归的方法,按照左中右的访问顺序,把所有节点的右子树递归的链接到最左边的节点上,形成一棵向左的扁平二叉树,然后再把它翻转到右边。
public void flatten(TreeNode root) {
if(root == null)
return;
TreeNode[] tail = new TreeNode[1]; //使用数组,使递归函数中修改的值能在其父节点中生效
tail[0] = root;
recursion(root, tail);
TreeNode curr = root;
while(curr.left != null){ //从左边翻转到右边
curr.right = curr.left;
curr.left = null;
curr = curr.right;
}
}
public void recursion(TreeNode root, TreeNode[] tail){
if(root == null){
return;
}
if(root.left != null){ //左节点,只需记录最末端节点,什么都不做
tail[0] = root.left;
recursion(root.left, tail);
}
if(root.right != null){ //右节点,把它链接到最左端的tail的左节点
tail[0].left = root.right;
root.right = null;
tail[0] = tail[0].left;
recursion(tail[0], tail);
}
}
方法二:按照右左中的顺序递归访问,并记录访问的前一个节点,把左子树链接到右节点上
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;
}