Redian新闻
>
non recursive binary tree traversal in O(n) time and O(1) space
avatar
non recursive binary tree traversal in O(n) time and O(1) space# JobHunting - 待字闺中
r*e
1
Question:
Write an O(n)-time nonrecursive procedure that, given an n-node binary tree,
prints out the key of each node. Use no more than constant extra space
outside of the tree itself and do not modify the tree, even temporarily,
during the procedure. Assume each node has a left pointer to its left child
, a right pointer to its right child, and no parent pointer.
Is this possible? Any ideas? Thanks.
avatar
v*7
2

tree,
child
I am wondering whether such solution exists. Traversal of a tree without
recursion
can be done by either Queue-based or Stack-based. But if the space required
is no
more than constant, it means that the space allocated to Queue or Stack is
constant.
But I have no idea on how to deal with it by using Q/S with constant space
forever.

【在 r******e 的大作中提到】
: Question:
: Write an O(n)-time nonrecursive procedure that, given an n-node binary tree,
: prints out the key of each node. Use no more than constant extra space
: outside of the tree itself and do not modify the tree, even temporarily,
: during the procedure. Assume each node has a left pointer to its left child
: , a right pointer to its right child, and no parent pointer.
: Is this possible? Any ideas? Thanks.

avatar
l*a
3
Your depth of the tree is non-constant. If there is not parent pointer,
no extra space to store the path from root to current node, how can you go
back once you are in the leaf.

tree,
child

【在 r******e 的大作中提到】
: Question:
: Write an O(n)-time nonrecursive procedure that, given an n-node binary tree,
: prints out the key of each node. Use no more than constant extra space
: outside of the tree itself and do not modify the tree, even temporarily,
: during the procedure. Assume each node has a left pointer to its left child
: , a right pointer to its right child, and no parent pointer.
: Is this possible? Any ideas? Thanks.

avatar
g*s
4
that's the answer: no way.

go

【在 l*****a 的大作中提到】
: Your depth of the tree is non-constant. If there is not parent pointer,
: no extra space to store the path from root to current node, how can you go
: back once you are in the leaf.
:
: tree,
: child

相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。