标签:des style http color os io for ar
Problem Description:
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
If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.
分析:按照题目的意思,将二叉树变为按先序序列排列的极端右子树形式,因此解题思路就是将二叉树按照先序遍历先把节点保存下来,然后按照要求重建二叉树即可,实际中采用了非递归的先序遍历,将节点保存到vector中,最后将重建二叉树。具体代码如下:
/** * Definition for binary tree * 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; vector<TreeNode *> vec; stack<TreeNode *> stk; TreeNode *p=root; while(p||!stk.empty()) { while(p) { vec.push_back(p); stk.push(p); p=p->left; } if(!stk.empty()) { p=stk.top(); stk.pop(); p=p->right; } } root=vec[0]; for(int i=0;i<vec.size()-1;i++) { vec[i]->left=NULL; vec[i]->right=vec[i+1]; } vec[vec.size()-1]->left=NULL; vec[vec.size()-1]->right=NULL; } };
Leetcode--Flatten Binary Tree to Linked List,布布扣,bubuko.com
Leetcode--Flatten Binary Tree to Linked List
标签:des style http color os io for ar
原文地址:http://blog.csdn.net/longhopefor/article/details/38581147