114. Flatten Binary Tree to Linked List - jiejackyzhang/leetcode-note GitHub Wiki

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

注意到root的右子树连接到它的左子树的最右边leaf下,然后root的左子树变成了它的右子树。 然后对于root.right同样操作。 这个过程可以通过iteration完成。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void flatten(TreeNode root) {
        while(root != null) {
            if(root.left != null) {
                TreeNode temp = root.left;
                while(temp.right != null) {
                    temp = temp.right;
                }
                temp.right = root.right;
                root.right = root.left;
                root.left = null;
            }
            root = root.right;
        }
    }
}
⚠️ **GitHub.com Fallback** ⚠️