Leetcode116 Solution

Q:
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

My solution

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if( root == nullptr) {
            return;
        }
        if(root->left != nullptr)
        {
            root->left->next = root->right;
        }
        if(root->right != nullptr && root->next != nullptr)
        {
            root->right->next = root->next->left;
        }
        connect(root->left);
        connect(root->right);
    }
};

這題初看,肯定會用BFS去解決(實際上是可以的),但是其實用DFS會更加方便。該解決方法的核心就是要注意到:root->right->next = root->next->left;

如果有任何疑問,歡迎留言,或者給我發郵件(liuhiter@gmail.com)。另外無恥求光顧本渣的gayhub leetcode項目。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 背景 一年多以前我在知乎上答了有關LeetCode的問題, 分享了一些自己做題目的經驗。 張土汪:刷leetcod...
    土汪閱讀 12,769評論 0 33
  • 目錄 簡書的 markdown 都不支持 [TOC] 語法……我就不貼目錄了。下面按照類別,列出了29道關于二叉樹...
    被稱為L的男人閱讀 3,379評論 0 8
  • 接近泥土的手 沾著花香 幾滴雨 幾縷光 一粒種 時 間 里 春始 夏長 秋永恒
    橘子zj閱讀 120評論 0 1
  • 樣本 | 師德建設的“德州模式”——山東省德州市采訪剪影(一)
    紫羅蘭_文竹閱讀 138評論 0 0
  • 昨天 做作業 找正裝找了半天也終于找到了。 今天 參加學代會,今天進行換屆選舉,我前去競選體育部副部長,不過要上臺...
    雷帥帥閱讀 163評論 0 0