感觉这个题像前序遍历,但是其实完全按preorder的话 我只能想到用两个stack 太不好了
看到用stack的iterative 入stack顺序和preorder不一样,才能保证出来的时候是这个顺序
即先push right 再push left,pop之后的右子设置为当前stack top
这个里面强调不要忘记将左子设置为null;
public void flatten(TreeNode root) { if (root == null) return;
Stack<TreeNode> stk = new Stack<TreeNode>();
stk.push(root);
while (!stk.isEmpty()){
TreeNode curr = stk.pop();
if (curr.right!=null)
stk.push(curr.right);
if (curr.left!=null)
stk.push(curr.left);
if (!stk.isEmpty()) //这里很重要,虽然while判断了stack是否空,但是最开始pop了
curr.right = stk.peek();
curr.left = null; // dont forget this!!
}
}
后面这个是不是用栈的方法,只用o(1)space 但是不好想
votes
1,290 views
class Solution {
public:
void flatten(TreeNode *root) {
TreeNode*now = root;
while (now)
{
if(now->left)
{
//Find current node's prenode that links to current node's right subtree
TreeNode* pre = now->left;
while(pre->right)
{
pre = pre->right;
}
pre->right = now->right;
//Use current node's left subtree to replace its right subtree(original right
//subtree is already linked by current node's prenode
now->right = now->left;
now->left = NULL;
}
now = now->right;
}
}
};