(LeetCode) 114. Flatten Binary Tree to Linked List

来源:互联网 发布:linux哪几种运行级别 编辑:程序博客网 时间:2024/05/17 06:04

114. 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

思路

题干的要求就是按照前序遍历的顺序抹平二叉树,所以只要前序遍历来操作即可。

代码

class Solution {public:    void flatten(TreeNode* root) {        if (root==NULL) return;        stack<TreeNode*> stk;        stk.push(root);        while(!stk.empty()){            TreeNode* cur = stk.top();            stk.pop();            if (cur->right != NULL) stk.push(cur->right);            if (cur->left != NULL) stk.push(cur->left);            if (!stk.empty()){                cur->right = stk.top();            }            cur->left = NULL;        }    }};
0 0