1. 程式人生 > >[LeetCode] 114. Flatten Binary Tree to Linked List Java

[LeetCode] 114. Flatten Binary Tree to Linked List Java

ini like lin ont == lis example 遞歸 font

題目:

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

題意及分析:給出一棵樹,要求給出這棵樹的先序遍歷組成的鏈表,但是還是用樹表示。首先找到根節點左子節點的最右子節點,然後將根節點的右子樹移到該點的右節點上;再將根節點的左子節點移到根節點的右子節點上,並將根節點左子樹重置為null;然後將根節點向右子節點移動一位,遞歸即可。

代碼:

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

[LeetCode] 114. Flatten Binary Tree to Linked List Java