LeetCode之flatten binary tree

问题描述:

/**
 * 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
 */

把一个二叉树flatten 成一个像链表一样的树,如上图所示。
可以看出,结果树就是二叉树前序遍历的结果顺序。
所以,可以先把二叉树前序遍历一下,把遍历的结果存储到队列queue当中,再构建新的结果二叉树即可。
代码如下:

public void flatten(TreeNode root) {
    if (root == null) return;
    Stack<TreeNode> stack = new Stack<TreeNode>();
    Queue<TreeNode> queue = new LinkedList<TreeNode>();
    stack.push(root);
    queue.add(root);
    while (!stack.isEmpty()) {
      TreeNode top = stack.peek();
      if (top.left != null) {
        queue.add(top.left);
        stack.push(top.left);
        top.left = null;
      } else if (top.right != null) {
          queue.add(top.right);
          stack.push(top.right);
          top.right = null;
      } else { //top.left == null && top.right == null
        stack.pop();
      }
    }
    TreeNode node = queue.poll();
    while (!queue.isEmpty()) {
      node.right = queue.poll();
      node = node.right;
    }
  }

上面这种方法借用了队列queue和栈stack。下面这种方法也很巧妙:

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

    private TreeNode findRightMost(TreeNode root) {
        if (root == null || root.right == null) return root;
        return findRightMost(root.right);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值