【c++】leetcode114 二叉树展开为链表

1.题目

leetcode114 二叉树展开为链表

2.解法

用栈实现非递归先序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include 
class Solution {
public:
    void flatten(TreeNode* root) {   
        if (root == NULL) return;   

        TreeNode* tmp = root;
        stack st = stack();
        st.push(root);
        while (st.size() != 0) {
            TreeNode *t = st.top();
            st.pop();
            if (t != root) {
                tmp->right = t;
                tmp->left = NULL;
                tmp = tmp->right;
            }
            if (t->right != NULL) st.push(t->right);
            if (t->left != NULL) st.push(t->left);
        }
    }
};

你可能感兴趣的:(刷题专栏,链表,c++,数据结构)