• Populating Next Right Pointers in Each Node


    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

    思路:通过递归,从root节点向下进行DFS。当遍历到一个节点时,如果它有孩子节点,则将左孩子的next指针指向右孩子。

    重点是右孩子的next指针该如何处理。在这里,我们每次递归时都向下传递一个指针,即当前节点的next指针。

    当我们要处理当前节点的右孩子next指针时,实际上它应该指向当前节点next指针所指向的节点的左孩子。

    此外,在递归时还要判断下,二叉树最右侧的节点的next指针都要为NULL。

     1 class Solution {
     2 public:
     3     void dfs(TreeLinkNode *root, TreeLinkNode *parent_next)
     4     {
     5         if (root->left == NULL) return;
     6         root->left->next = root->right;
     7         root->right->next = (parent_next) ? 
     8             parent_next->left : NULL;
     9         dfs(root->left, root->left->next);
    10         dfs(root->right, root->right->next);
    11     }
    12     void connect(TreeLinkNode *root) {
    13         if (root == NULL) return;
    14         dfs(root, NULL);
    15     }
    16 };
  • 相关阅读:
    IDEA提交项目到SVN
    动态代理
    eclipse安装svn,初次提交项目到svn
    异常信息:java.lang.IllegalStateException: Cannot forward after response has been committed
    网上商城订单
    学生选课系统
    分页
    用户注册登录 和 数据写入文件的注册登录
    第一次考试(基础部分)
    小数和质数问题
  • 原文地址:https://www.cnblogs.com/fenshen371/p/4913657.html
Copyright © 2020-2023  润新知