首页 > 代码库 > Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

 

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

         1        /        2   5      / \        3   4   6

 

The flattened tree should look like:
   1         2             3                 4                     5                         6

click to show hints.

Hints:

If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.

使用先序遍历迭代方式,直接代码如下:

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     void flatten(TreeNode *root) {  //使用线序遍历的迭代方式13         if( !root ) return;14         stack<TreeNode*> qt;15         qt.push(root); 16         TreeNode* pre = 0;  //记录前驱节点17         while( !qt.empty() ) {18             TreeNode* cur = qt.top();19             qt.pop();20             if( cur->right ) qt.push(cur->right);   //先放右子树21             if( cur->left ) qt.push(cur->left);     //再放左子树22             if( pre ) { //如果前驱节点不为空的情况下23                 pre->right = cur;24                 pre->left = 0;25             }26             pre = cur;  //更新前驱节点27         }28         pre->right = 0;29         pre->left = 0;30     }31 };

 

Flatten Binary Tree to Linked List