码迷,mamicode.com
首页 > 其他好文 > 详细

Flatten Binary Tree to Linked List

时间:2015-08-28 19:32:28      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

二叉树先序遍历,之后做成链表

 1 /**
 2  * Definition for a binary tree node.
 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==NULL)
14             return;
15         stack<TreeNode *> st1;
16         st1.push(root);
17         TreeNode * last=NULL;
18         while(!st1.empty())
19         {
20             TreeNode * temp=st1.top();
21             st1.pop();
22             
23             if(temp->right!=NULL)
24                 st1.push(temp->right);
25             if(temp->left!=NULL)
26                 st1.push(temp->left);
27 
28             temp->left=NULL;
29             temp->right=NULL;
30             if(last!=NULL)
31                 last->right=temp;
32             last=temp;
33         }
34     }
35 };

 

Flatten Binary Tree to Linked List

标签:

原文地址:http://www.cnblogs.com/aguai1992/p/4767533.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!