标签:一个 one multi 入栈 nat sse comment content lan
问题亟待解决:
1.一个问题一直困扰着我,想看下别人是怎么处理树的输入的,最好是以层级遍历这种清楚直观的方式。
2.关于指针*的使用
因此也导致代码不完整,没有主函数对Solution类的调用
Given a binary tree
struct Node { int val; Node *left; Node *right; Node *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
.
Follow up:
Example 1:
Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with ‘#‘ signifying the end of each level.
本题是上一题的变形,区别:
上一个完全二叉树不用区分具体树的节点是否存在,对树的遍历就有递归和非递归两种。递归方法会有不同,但非递归方法
还可以适用。非递归方法很好的一点在于,和栈的结合,将存在的元素压入栈,就忽视了树本身带来的影响。这个方法在时空
复杂度上都表现的非常好,虽然有两重循环,但循环执行的次数比较少估计是原因
#include<bits/stdc++.h> /* multi-line comment */ using namespace std; // Definition for a Node. class Node { public: int val; Node* left; Node* right; Node* next; //three different kinds initialize Node() : val(0), left(NULL), right(NULL), next(NULL) {} Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {} Node(int _val, Node* _left, Node* _right, Node* _next) : val(_val), left(_left), right(_right), next(_next) {} }; //definition of solution class Solution{ public: Node* connect(Node* root){ //special case deal if(!root) return NULL; //define queue store list by line queue<Node*> q; q.push(root); //still have node not iterating while(!q.empty()) { int len=q.size(); for(int i=0;i<len;++i) { Node *t=q.front(); q.pop(); if(i<len-1) t->next=q.front(); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } } return root; } };
LeetCode开心刷题五十五天——117. Populating Next Right Pointers in Each Node II
标签:一个 one multi 入栈 nat sse comment content lan
原文地址:https://www.cnblogs.com/Marigolci/p/12008181.html