【LeetCode-面試演算法經典-Java實現】【116-Populating Next Right Pointers in Each Node(二叉樹連結右指標)】

來源:互聯網
上載者:User

標籤:二叉樹   連結   演算法   面試   java   

【116-Populating Next Right Pointers in Each Node(二叉樹連結右指標)】 【LeetCode-面試演算法經典-Java實現】【所有題目目錄索引】 原題

  Given a binary tree

    struct TreeLinkNode {      TreeLinkNode *left;      TreeLinkNode *right;      TreeLinkNode *next;    }

  Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
  Initially, all next pointers are set to NULL.
  Note:
  You may only use constant extra space.
  You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
  For example,
  Given the following perfect binary tree,

         1       /        2    3     / \  /     4  5  6  7

  After calling your function, the tree should look like:

         1 -> NULL       /  \      2 -> 3 -> NULL     / \  / \    4->5->6->7 -> NULL

題目大意

  給定一棵二叉樹,有一個next指標,將它們的每一層連結起來。只能使用常量額外空間,樹是一棵完美二叉樹。

解題思路

  將樹的每一層節點用next串起來。這樣每一層也會形成一個單鏈表。而每層的鏈表頭,則是,根的左孩子,左孩子,左孩子。利用雙迴圈,外層迴圈,沿著根的左孩子,一直向下。內層迴圈,負責將下一層的節點串起來。即,將自己右孩子放到左孩子的next上,而右孩子,則可通過自己的next指標,找到右鄰居。

代碼實現

樹結點類

public class TreeLinkNode {    TreeLinkNode left;    TreeLinkNode right;    TreeLinkNode next;}

演算法實作類別

public class Solution {    public void connect(TreeLinkNode root) {        TreeLinkNode node;        // 題中假設了輸入的樹是一棵完全叉樹        // 第一個迴圈用來處理整個樹        // root.left != null如果不用,則處理到最後第一個沒有左右子樹的結點會出錯        while (root != null && root.left != null) {            // 每個root表示第一個層的第一個結點            // node記錄每一個層的第一個結點            node = root;            // 處理每個層            while (node != null) {                // 表示串連的是同一個結點的下的兩子結點                node.left.next = node.right;                // node不是某個層的最後一個結點                if (node.next != null) {                    // 將這個結點的右子結點串連到這個結點的同層相鄰結點的左子結點上                    node.right.next = node.next.left;                }                // 移動到同層的下一個結點                node = node.next;            }            // 移動到下一層的第一個結點            root = root.left;        }    }}
評測結果

  點擊圖片,滑鼠不釋放,拖動一段位置,釋放後在新的視窗中查看完整圖片。

特別說明 歡迎轉載,轉載請註明出處【http://blog.csdn.net/derrantcm/article/details/47438089】

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

【LeetCode-面試演算法經典-Java實現】【116-Populating Next Right Pointers in Each Node(二叉樹連結右指標)】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.