[LeetCode] Flatten Binary Tree to Linked List,leetcodeflatten

來源:互聯網
上載者:User

[LeetCode] Flatten Binary Tree to Linked List,leetcodeflatten

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

大象放入冰箱幾步的思路處理這問題就好了

1.把左子樹弄平, 2. 插入到根節點和根節點的右子樹之間,3. 重複1,2

思路不難,代碼上有點混亂,細節實現是:把root的左子樹弄成flatten的 flatten(root.left),把右子樹儲存起來 temp=root.right,讓root.right=root.left, 然後斷掉左邊,root.left=null.

然後一直走到右邊的最末端,while(root.right!=null) root=root.right  然後root.right=temp,繼續處理。

 一次通過,代碼如下:

public void flatten(TreeNode root) {        if(root==null) return;        TreeNode p=root;        while(p!=null){            if(p.left==null){                p=p.right;            } else {                if(p.right==null) {                    TreeNode temp=p.left;                    p.left=null;                    p.right=temp;                    p=p.right;                } else {                                TreeNode tempRight=p.right;                TreeNode tempLeft=p.left;                p.right=null;                flatten(p.left);                p.left=null;                p.right=tempLeft;                while(p.right!=null){                    p=p.right;                }                p.right=tempRight;                }            }                    }            }





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.