/**
* 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*> nodeStack;
nodeStack.push(root);
while(nodeStack.size())
{
root = nodeStack.top();
nodeStack.pop();
if(root->right)
nodeStack.push(root->right);
if (root->left)
nodeStack.push(root->left);
root->left = NULL;
if (nodeStack.size())
root->right = nodeStack.top();
else root->right = NULL;
}
}
};
void flatten(TreeNode *root)
{
if (root == NULL) return;
while (root)
{
{
TreeNode *pre = root->left;
while (pre->right)
pre = pre->right;
pre->right = root->right;
root->right = root->left;
root->left = NULL;
}
root = root->right;
}
}
二叉树遍历应用114. Flatten Binary Tree to Linked List
最新推荐文章于 2022-09-06 16:04:14 发布