二叉树展开为链表

给定一个二叉树,原地将它展开为链表。

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6

将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

思路:采用后序遍历,将左子树放在右子树的位置上,然后再把右子树跟在左子树最右节点的右子树上。

public class Flatten {
	public class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}

	public void flatten(TreeNode root) {
		if (root == null) {
			return;
		}
		flatten(root.left);
		flatten(root.right);
		if (root.left != null) {
			TreeNode left = root.left;
			TreeNode right = root.right;
			root.right = root.left;
			root.left = null;
			while (left.right != null) {
				left = left.right;
			}
			left.right = right;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/gkq_tt/article/details/88720641