LeetCode: Flatten Binary Tree to Linked List
Title:
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
思路:递归版本的。主要还是前序递归,使用一个前向指针,用来判断当前的节点是不是前向指针的右子节点,如果不是,那么前向指针的右节点就是当前的节点
/** * 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: TreeNode* tail; Solution(){ tail = NULL; } void flatten(TreeNode* root) { maker(root); } void maker(TreeNode* p){ if (!p) return ; TreeNode* left = p->left; TreeNode* right = p->right; if (tail){ tail->right = p; tail->left = NULL; } tail = p; maker(left); maker(right); } };
非递归的更简洁。使用栈,让右节点先进去。这样栈顶就是左节点,所以在两个子节点进栈之后,让当前root节点的右节点指向栈顶
/** * 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 == nullptr) return; stack<TreeNode*> s; s.push(root); while (!s.empty()) { auto p = s.top(); s.pop(); if (p->right) s.push(p->right); if (p->left) s.push(p->left); p->left = nullptr; if (!s.empty()) p->right = s.top(); } } };