Thursday, May 14, 2015

Form A Linked List From the Leaves Of A Binary Tree

来源:EPI

原帖:EPI 6.10 pg. 237.

题目:
Given a binary tree, write a function which forms a linked list from the leaves of the binary tree. The leaves should appear in left-to-right order. For example, when applied to the binary tree in Figure 6.1 on Page 55, your function should return <D, E, H, M, N, P>.

代码:
 struct BinaryTree {  
   int data;  
   BinaryTree* left;  
   BinaryTree* right;  
   BinaryTree(int d) : data(d), left(NULL), right(NULL) {}  
 };  
   
 void connect_leaves_helper(BinaryTree* root, list<BinaryTree*>& l) {  
   if (root) {  
     if (!root->left && !root->right) {  
       l.push_back(root);  
       return;  
     } else {  
       connect_leaves_helper(root->left, l);  
       connect_leaves_helper(root->right, l);  
     }  
   }  
 }  
   
 vector<BinaryTree*> connect_leaves(BinaryTree* root) {  
   vector<BinaryTree*> L;  
   connect_leaves_helper(root, L);  
   return L;  
 }  

No comments:

Post a Comment