Given a binary tree
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
Initially, all next pointers are set to
NULL.Initially, all next pointers are set to
NULL.Example 1:
Input: root = {1,2,3,4,5,null,7}
Output: [1,#,2,3,#,4,5,7,#]Approach
Java
import java.util.ArrayList;import java.util.LinkedList;import java.util.List;import java.util.Queue;public class PopulatingNextRightPointersII {public static void main(String[] args) {Node root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.right = new Node(7);Node root1 = connect(root);printTree(root1);}// function to connect nodes at the// each levelstatic Node connect(Node root) {Queue<Node> q = new LinkedList<>();if (root == null)return null;q.add(root);while (!q.isEmpty()) {int len = q.size();Node prev = null;while (len > 0) {len--;Node temp = q.poll();if (temp == null)continue;if (prev != null)prev.next = temp;elseprev = null;prev = temp;q.add(temp.left);q.add(temp.right);}}return root;}//function to print the treestatic void printTree(Node root) {Queue<Node> q = new LinkedList<>();q.add(root);List<String> vec = new ArrayList<String>();while (!q.isEmpty()) {int len = q.size();while (len > 0) {len--;root = q.poll();if (root != null) {vec.add(String.valueOf(root.val));q.add(root.left);q.add(root.right);}}vec.add("#");}for (int i = 0; i < vec.size() - 2; i++)System.out.print(vec.get(i) + ",");System.out.println(vec.get(vec.size() - 2));}static class Node {int val;Node left;Node right;Node next;Node(int val) {this.val = val;this.next = null;this.right = null;this.left = null;}}}
C++
#include <bits/stdc++.h>using namespace std;struct Node {int val;Node *left;Node *right;Node *next;Node(int val){this->val=val;this->next=NULL;this->right=NULL;this->left=NULL;}};//function to connect nodes at the//each levelNode* connect(Node* root){queue<Node*> q;if(root==NULL)return NULL;q.push(root);while(!q.empty()){int len=q.size();Node *prev=NULL;while(len--){Node *temp=q.front();q.pop();if(temp==NULL)continue;prev?(prev->next=temp):NULL;prev=temp;q.push(temp->left);q.push(temp->right);}}return root;}//function to print the treevoid printTree(Node *root){queue<Node*>q;q.push(root);vector<string> vec;while(!q.empty()){int len=q.size();while(len--){root=q.front();q.pop();if(root!=NULL){vec.push_back(to_string(root->val));q.push(root->left);q.push(root->right);}}vec.push_back("#");}for(int i=0;i<vec.size()-2;i++)cout<<vec[i]<<",";cout<<vec[vec.size()-2];}int main(){Node *root=new Node(1);root->left=new Node(2);root->right=new Node(3);root->left->left=new Node(4);root->left->right=new Node(5);root->right->right=new Node(7);Node *root1=connect(root);printTree(root1);return 0;}
No comments:
Post a Comment