114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example, given the following tree:

    1
   / \
  2   5
 / \   \
3   4   6

The flattened tree should look like:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

难度:medium

题目:给定二叉树,原地扁平化。

思路:后序遍历

Runtime: 6 ms, faster than 100.00% of Java online submissions for Flatten Binary Tree to Linked List.
Memory Usage: 40 MB, less than 100.00% of Java online submissions for Flatten Binary Tree to Linked List.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        rightFlatten(root);
    }
    
    private TreeNode rightFlatten(TreeNode root) {
        if (null == root) {
            return root;
        }
        TreeNode left = rightFlatten(root.left);
        TreeNode right = rightFlatten(root.right);
        if (left != null) {
            root.left = null;
            root.right = left;
            TreeNode rightMost = left;
            while (rightMost.right != null) {
                rightMost = rightMost.right;
            }
            rightMost.right = right;
        }
        
        return root;
    }
}
    原文作者:linm
    原文地址: https://segmentfault.com/a/1190000018180900
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞