您的位置:首页 > 其它

Flatten Binary Tree to Linked List

2015-08-28 18:10 627 查看
https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

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

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(root==NULL)
return;
stack<TreeNode *> st1;
st1.push(root);
TreeNode * last=NULL;
while(!st1.empty())
{
TreeNode * temp=st1.top();
st1.pop();

if(temp->right!=NULL)
st1.push(temp->right);
if(temp->left!=NULL)
st1.push(temp->left);

temp->left=NULL;
temp->right=NULL;
if(last!=NULL)
last->right=temp;
last=temp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: