首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。