Leetcode刷題java之114. 二叉樹展開爲鏈表

執行結果:

通過

顯示詳情

執行用時 :0 ms, 在所有 Java 提交中擊敗了100.00% 的用戶

內存消耗 :35.8 MB, 在所有 Java 提交中擊敗了86.84%的用戶

題目:

給定一個二叉樹,原地將它展開爲鏈表。

例如,給定二叉樹

    1
   / \
  2   5
 / \   \
3   4   6

將其展開爲:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

思路:

有點嫁接的意味,找到左子樹的最右節點,然後讓他的最右節點等於根的右節點,然後讓根的右節點等於根的左節點。

參考https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list/solution/xiang-xi-tong-su-de-si-lu-fen-xi-duo-jie-fa-by--26/

代碼:

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

 

發佈了476 篇原創文章 · 獲贊 485 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章