The programmer interview template outputs single-layer nodes and the programmer interview template.
[Disclaimer: All Rights Reserved. indicate the source for reprinting. Do not use it for commercial purposes. Contact mailbox: libin493073668@sina.com]
Question link: http://www.nowcoder.com/practice/cb6c883b123b44399377d0c71e6ba3ea? Rp = 1 & ru =/ta/cracking-the-coding-interview & qru =/ta/cracking-the-coding-interview/question-ranking
Description
For a binary tree, design an algorithm to create a linked list containing all nodes in a depth.
Given the root node pointer TreeNode * root of the Binary Tree and the depth of the node on the linked list, return a ListNode linked list, which represents the value of all nodes in the depth, follow the link from left to right on the tree to ensure that the depth does not exceed the height of the tree. The Node value on the tree is a non-negative integer and cannot exceed 100000.
Ideas
If you have done a similar question before, this question is actually quite simple. The Traversal method is nothing more than the depth priority and breadth priority. It is definitely not feasible to give priority to the depth of this question, we know that breadth first is divergent walking, so we can use breadth first to complete this question and save all nodes at the same layer in the queue.
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*//*struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) {}};*/class TreeLevel{public:ListNode* getTreeLevel(TreeNode* root, int dep){// write code hereif(root==nullptr)return nullptr;queue<TreeNode*> Q,tmp;Q.push(root);int cnt = 1;ListNode *newList = new ListNode(0);ListNode *pNode = newList;while(!Q.empty()){if(cnt==dep){while(!Q.empty()){ListNode *newNode = new ListNode(Q.front()->val);Q.pop();pNode->next = newNode;pNode = pNode->next;}}while(!Q.empty()){TreeNode *cur = Q.front();Q.pop();tmp.push(cur->left);tmp.push(cur->right);}while(!tmp.empty()){Q.push(tmp.front());tmp.pop();}++cnt;}return newList->next;}};
Copyright Disclaimer: This article is the original article of the blogger. If it is reproduced, please indicate the source