LeetCode-Populating Next Right Pointers in Each Node-填充结点的右指针-二叉树递归
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-Populating Next Right Pointers in Each Node-填充结点的右指针-二叉树递归
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
構造一個按深度索引的數組,存儲的當前遍歷的結點在這一層的最右邊的結點。
由前序遍歷的特點可知同一層左邊的兒子先被訪問,過一段時間后會訪問右邊的兒子。利用這個特點連接next數組即可。
需要注意vec.size()-1在vec=0時不是-1,而是一個很大的整數(溢出了)。
/*** 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) {}* };*/typedef TreeLinkNode scnode; class Solution { public:vector<scnode *> ps;void PreOrder(scnode *rt,int l){if (rt==NULL) return;if (l+1>ps.size()){ps.push_back(NULL);}if (ps[l]!=NULL) ps[l]->next=rt;ps[l]=rt;rt->next=NULL;PreOrder(rt->left,l+1);PreOrder(rt->right,l+1);}void connect(TreeLinkNode *root) {PreOrder(root,0);} };?
轉載于:https://www.cnblogs.com/yangsc/p/4025150.html
總結
以上是生活随笔為你收集整理的LeetCode-Populating Next Right Pointers in Each Node-填充结点的右指针-二叉树递归的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Cucumber 入门一
- 下一篇: ●类(2)、接口