Skip to content

Conversation

@docto-rin
Copy link
Owner

@docto-rin docto-rin mentioned this pull request Oct 23, 2025
- 最初に思いついた方法は、inorder(中間順), bottom-up -> postorder(後行順), top-down -> preorder(先行順)とまとめ直せる。
- Q. 任意のrecursive解法は、iterativeでも書ける、と考えて良さそうですか?
- > A. 再帰は「スタック操作の構文糖」であり、構文糖を展開すれば必ず iterative にできる。ただし、**人間にとっての可読性・メンテ性**の観点では再帰のほうがしばしば自然。常にiterativeに直すべきとは限りません。
- これ、当たり前なはずですが、自分はしばしばiterativeで書き直すことに苦労してます。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

特に返り値を利用した再帰だと面倒です。


### 実装5

- inorderをiterativeに実装。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

このあたりで inorder を iterative にする話があります。
https://discord.com/channels/1084280443945353267/1200089668901937312/1201416402247098398


### 実装7

- bottom-up(帰りがけ)をiterativeで書く方法。
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

一応、私が帰りがけ iterative でイメージしたものと違ったので書いておきます。

class Solution:
    def isValidBST(self, root: Optional[TreeNode]) -> bool:
        stack = [([], root, [], [])]
        while stack:
            from_to, node, left, right = stack[-1]
            if not left and node.left:
                stack.append((left, node.left, [], []))
                continue
            if not right and node.right:
                stack.append((right, node.right, [], []))
                continue
            if left and left[1] >= node.val:
                return False
            if right and node.val >= right[0]:
                return False
            r = left + [node.val] + right
            from_to += [min(r), max(r)]
            stack.pop()
        return True

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants