欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode·114. Flatten Binary Tree to Linked List

程序员文章站 2022-03-07 23:39:44
...

思路:先序遍历

/**
 * 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*> st;
        st.push(root);
        TreeNode* fn = root;
        TreeNode* fr = root;
        while(!st.empty()){
            fn = st.top();
            if(fn != root){
                fr->right = fn;
                fr->left = NULL;
                fr = fn;
            }
            st.pop();
            if(fn->right != NULL)
                st.push(fn->right);
            if(fn->left != NULL)
                st.push(fn->left);
        }
    }
};


LeetCode·114. Flatten Binary Tree to Linked List