Binary transfer list

114. The binary tree expands to list

Given a binary tree, place it expands the list.

For example, a given binary tree

  1
    / \
  25
   / \ \
 346
to expand as:

1
  \
    2
       \
    3
           \
             4
     \
      5

       \
      6

/**
 * 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) {
        if(root == null) return;
        TreeNode cur = root;
        while(cur != null){
            if(cur.left != null){
                TreeNode p = cur.left;
                while(p.right != null) p = p.right; 
                p.right = cur.right;
                cur.right = cur.left;
                cur.left = null;
            }
            cur = cur.right;
        }
    }
}

 

Guess you like

Origin www.cnblogs.com/zzytxl/p/12563561.html