Talk:Tree traversal

message: Algorithm requires a check if a node has been already printed other wise it will always keep 
on printing the leftmost and its parent. —Preceding unsigned comment added by 66.235.10.126 (talk • contribs) 30 December 2005
:Thanks! When doing the recursive to iterative translation I forgot to keep in mind that we somehow have to remember the code position at the last call. I'll ponder how to do this in a neat clean way. Deco 10:59, 30 December 2005 (UTC)
thread_title:  Iterative Inorder Traversal 

message: The currently presented iterative algorithm I find a little too obscure.  For reference, here it is:
 visit(root) {
     prev    := null
     current := root
     next    := null
    
     while current ≠ null {
         if prev == current.parent
             prev := current
             next := current.left
         if next == null or prev == current.left
             print current.value
             prev := current
             next := current.right
         if next == null or prev == current.right
             prev := current
             next := current.parent
         current := next
     }
 }
For a few days, the following version was in the article:
 visit(root) {
     prev    := null
     current := root
     next    := null
    
     while current ≠ null {
         if prev == current.parent
             next := current.left
         if next == null or prev == current.left
             print current.value
             next := current.right
         if next == null or prev == current.right
             next := current.parent
         prev := current
         current := next
     }
 }
It's a little simpler because the "prev := current" has been factored out.  But it doesn't work in some cases because of subtleties in the code.  It's not a simple factoring because in the original the "prev := current" affected the if statements which followed it, which the factored version does not.  Only occasionally does that matter.
One case it fails for is where the root has only one child, a left-hand child. After taking the first then clause ("next := current.left") it mistakenly executes the third then clause ("next := current.parent") causing next to be set to null and the loop to be exited.  This is because the test "prev == current.right" succeeds since both values are null.  In the original/current code, this failure was prevented by the earlier execution of "prev := current".
I think the current algorithm is too subtle to be a good example.  I'm looking at modifications to clarify it. -R. S. Shaw 03:27, 9 June 2006 (UTC)
replies: text: Ah, I see.  I didn't take into account the fact that the flow of execution fell through to the next if statement.  Al 03:44, 9 June 2006 (UTC)

text: I agree. I wrote it. If you can come up with anything simpler that would be great. Deco 09:10, 9 June 2006 (UTC)
replies: text: After looking at some alternatives, I've put in a new version of the algorithm.  This one uses a nested subroutine (for something that could have just been duplicate code) because it seemed a little clearer despite the extra routine. -R. S. Shaw 00:17, 10 June 2006 (UTC)
replies: text: Personally I find that more complicated, since "midvisit" doesn't seem to have a clear conceptual role. Maybe I'm missing something. Deco 01:20, 10 June 2006 (UTC)
thread_title:  Iterative Traversal Redux 

message: I rewrote the article, removing implementations, as they were probably incorrect, according to the various comments on them, and as implementations don't replace a good explanation. I consider the article to be a stub now, and valid and clean implementations could be added (I plan to). I also didn't keep the external links, that were not even really related to tree traversal, but merely to the use of graphs in the context of database, and probably came from a web development background (PHP and MySQL related links).
There are surely far better and more classic references to the subject, but the O'Reilly book is the one where I learned tree traversal and where I verified my stub. In particular, I suspect there is a treatment of trees and corresponding algorithms in The Art of Computer Programming, but I don't have it at hand.
Nowhere man 22:15, 1 December 2006 (UTC)
thread_title:  Rewrite 

message: To anyone watching this article, let me know what you think of the modifications. Restructured it quite a bit, no doubt slipped some typos/mistakes in, but I tried to make it look a bit more professional.
Also changed all the pseudocode to be consistent with one another (some were using curly braces to mark blocks, others just used whitespace - I started at the top where there was whitespace delimited blocks, and made the rest like that), and completely changed the algorithm for iterative/explicit stack based traversals.  Let me know if I stuffed it up ! The original code definitely works, but it's possible I mucked up the pseudocode translation. Benefit of the new pseudocode is that at any point the direction could be changed (just use rights instead of lefts, lefts instead of rights), even mid traversal... and that the stack based implementation is virtually identical to the parent pointers implementation.
Also added an example for how to in-order traverse a threaded tree.
Phew. Over an hour down the drain, hope somebody finds it useful =P
Themania 06:24, 28 February 2007 (UTC)
replies: text: It looks great. I'll be reviewing it for stylistic concerns, but that's a lot of useful information you've added in. — Edward Z. Yang(Talk) 22:48, 28 February 2007 (UTC)
replies: text:  Thanks Edward =) apologies about reverting your revert - I'm pretty confident that the anomynous ip-logged user was correct, although reverting reverts should probably be mentioned on the talk page..? —The preceding unsigned comment was added by Themania (talk • contribs) 00:11, 1 March 2007 (UTC)
replies: text:  No, it's okay. It's tough to tell whether or not an edit is legit when there's no edit summary given. — Edward Z. Yang(Talk) 02:29, 1 March 2007 (UTC)
replies: text:  Would be, especially for non user edits. Just reassuring to know that there's people watching =) Themania 15:15, 1 March 2007 (UTC)
thread_title:  Changes on 14 Feb 07 

message: inorder(node)
 while hasleftchild(node) do
   node = node.left
 do
   visit(node)
   if not (hasrightchild(node)) then
     node = node.right // <------------------ look here
   else
     node = node.right // <------------------ and here
   while hasleftchild(node) do
     node = node.left
 while node ≠ null
This can't be right... 
Philfreo 18:59, 23 March 2007 (UTC)
replies: text: You're right, it's wrong.  The inner while should have been under the then.  I've fixed the article.  Note that this is not just some iterative solution, it is only for a threaded tree, which essentially always has pointers to skip directly to the next inorder node from a node without a right child, so it happens to have a very simple inorder walk because of the extra threading. -R. S. Shaw 03:31, 24 March 2007 (UTC)

text: Apparently you're overlooking the word threaded.  It's important.  See Threaded binary tree. -R. S. Shaw (talk) 22:34, 13 February 2008 (UTC)
thread_title:  Problem with Iterative Solution 

message: This article seem to focus exclusively on the traversal of binary trees. My question is, if we want to include something about, for instance, traversal of directories on disk, should the focus of this article be changed, or should it be renamed to "binary tree traversal" and a more general article started? I am leaning towards the latter, but want more input than my own before I do it. W (talk) 13:55, 9 May 2008 (UTC)
replies: text: I think we should just change everything to support all kinds of trees and mention somewhere how they can be done a little differently for binary trees. asmeurer (talk | contribs) 18:42, 2 July 2012 (UTC)
replies: text:  Agreed. The use of the terms "left" and "right" is very misleading for a "tree traversal" article and might lead people who don't know any better to think that all trees are binary.  — Preceding unsigned comment added by 82.9.176.129 (talk) 02:22, 24 February 2014 (UTC)

text: I agree, I was shocked to see only binary trees were used as illustrations (images) and implementations. It is mentioned in the article, but it really should be either renamed or rewritten to be more generic. The current article is misleading. PhiLho   — Preceding undated comment added 22:55, 7 August 2014 (UTC)
thread_title:  Non-binary trees 

message: Hi, i'm sry, but i don't really understand why the inorder-way in the example ends with "H I" and not with "I H". G's the first right child of the root. There's no left child of G, so we go to I and I' only child is H, so my intuition says there's no way in generell to "skip" a node. And is there a difference mentionable between "rightnode" and "rightchild" ? (btw is there a reason to write rightchild together or divided "right child"...). Sorry for faultily english. If someone's got the time please post me here that the question is answered. Thx a lot. --WissensDürster (talk) 19:29, 24 January 2009 (UTC)
replies: text: I guess this answer would help you right now but maybe someone else will read it. I'd agree that the order is wrong for the "inorder" example. It doesn't make sense to skip this node. G I H should ne the right order! 188.101.213.177 (talk) 10:52, 15 August 2012 (UTC)
thread_title:   Traversal - Example 

message: All the kinds of traversal say, e.g. 'visit the left subtree; visit the root; visit the right subtree'
Surely it should be 'visit the node' rather than 'visit the root'. 
We do NOT keep going back to the root. JamesHDavenport (talk) 23:04, 17 March 2010 (UTC)
replies: text: Sure, but the article is titled "tree traversal", not "binary tree traversal", even though the term "left subtree" is completely meaningless for most other types of tree structure. The problem here is that the article uses very tree-type-specific and context-specific language and yet purports to be about trees in general.  — Preceding unsigned comment added by 82.9.176.129 (talk) 02:27, 24 February 2014 (UTC)
thread_title:  Traversal - Terminology 

message: I'm not convinced iterativePostorder() is correct. I've tried coding it up in Java and could not get it to work - although I accept it may be my own inability! A post-order tree traversal is the most difficult to implement of all the methods.
What I do know is that the pseudo code is poorly formatted with respect to the if-elseif-else block. The use of brackets may take up more lines but eliminates error and reader confusion.
I have a slight problem with the algorithms presented. They are primarily for binary trees with the nodes having left and right child nodes. However, the article title is "Tree Traversal" and not "Binary Tree Traversal". Thus, any algorithms presented should strictly be for general trees; ie a variable list of child nodes. This is what I'm trying to implement, the reason why I looked at this article and as a result have found the article confusing and of little use for general tree traversal.  — Preceding unsigned comment added by 81.187.174.42 (talk) 09:48, 11 August 2011 (UTC)
thread_title:  iterativePostorder()?? 

message: I have given a reference for the Recursive Traversals in C section. I've also put a  tag under the section References. Please cite the books and the pdf properly in their respective places. This will make the page look good and maintain uniformity. Thanks! BPositive (talk)  08:00, 6 December 2011 (UTC)
thread_title:  References and proper citing 

message: I've replaced this code with a version that is more clear and practical for use. It only needs to keep the current node and not the previous node, so it can easily be expressed as a pair of first/next functions. The code is from my AVL tree at http://code.google.com/p/badvpn/source/browse/trunk/structure/BAVL.h#685 and I've been using it for a long time with no problems. 193.77.101.149 (talk) 00:23, 20 July 2012 (UTC)
thread_title:  Iterative traversal with parent pointers 

message: Does anyone know a use for it? (If not, can I just add that it's useless and make someone prove otherwise? Just kidding.) Will Faught (talk) 22:20, 26 August 2012 (UTC)
thread_title:  Postorder conspicuously missing from 'Uses' section 

message: The main article treats binary trees inherently as a nonlinear data structure, however they can be easily mapped to one (see https://en.wikipedia.org/wiki/Binary_tree#Arrays for a nice pictorial example). As a linear data structure, the traversal is trivial. This requires that the map to the linear array follows the traversal desired.
These mappings do not provide for fast (re)balancing. Groups of nodes are implied by the positions in the array, so moving a group generally requires moving the contents of all associated nodes (as opposed to generic binary trees).
In addition to an accelerated traversal, these maps provide controlled data locality, potentially improving performance in tree searches (which these structures are typically used for). Allocation on the fly guarantees no data locality at all, which reduces the efficiency of both tree searches and traversals.
As a result, linear mapped binary trees are particularly suited for fast tree searches and traversals on static binary search trees, where the tree structure is preserved (though member variables may change).
Qm physics (talk) 04:32, 10 March 2014 (UTC)
thread_title:  Traversals on linearly mapped binary trees 

message: The sentence containing these 2 phrases is quite clumsy.  I'm not even sure what is really meant, but perhaps "using recursion" and "using corecursion" express the idea properly.  — Preceding unsigned comment added by 68.183.92.210 (talk) 20:25, 14 May 2014 (UTC)
thread_title:  including recursively / including corecursively  

message: "It is more prone to errors when both the children are not present and both values of nodes point to their ancestors" is nonsensical.   It implies that no (or maybe 1?) children are present, but the values point to something?!  — Preceding unsigned comment added by 68.183.92.210 (talk) 21:27, 14 May 2014 (UTC)
thread_title:  Morris threading 

message: There are several broken links pointing to and within this page. E.g. https://en.wikipedia.org/wiki/Inorder_traversal#Inorder_traversal (not sure where I found that link). Additionally links are broken within the page, e.g. "threading the tree"
I don't know enough about editing Wikipedia to know a way to find all these links but I thought I would point it out as there seems to have been some work done on this. Thanks!
Chris Alexander UK (talk) 19:10, 19 May 2014 (UTC)
thread_title:  Broken links 

message: Foregoing was herein the talk #Iterative traversal with parent pointers (see section above), a new section in the article called "Iterative in-order and without callback" by user:Nomen4Omen, a revert by user:Altenmann with the grounds "Rv primary source nonnotable. (TW)" and a user talk page discussion between user:Nomen4Omen and user:Altenmann:
In User talk:Altenmann#tree traversal:
Dear Altenmann, you reverted my new section in "Tree traversal" because "primary source nonnotable. (TW)". What do you mean by that: Is the reference to Ben Pfaff defective? What about the other pseudocode examples which do not carry any reference at all? And have a  since June 2013 and are still in the article? Pls answer in your user talk page. Best regards, --Nomen4Omen 08:07, 27 August 2015 (UTC)
replies: text: Dear Altenmann, you reverted several edits and again the section "Nonrecursive tree traversal by iteration" in Tree traversal because "Rv unreferened original research". You certainly know that it is NOT original research − see the mentioned sources Pfaff and Sedgewick, although Sedgewick is not completely explicit. But there is also http://code.google.com/p/badvpn/source/browse/trunk/structure/BAVL.h#685. Would it help you adding this one? Best regards, --Nomen4Omen (talk) 08:00, 10 September 2015 (UTC)
thread_title:  New section "Non-recursive tree traversal by Iteration" 

message: "Trees can be traversed in pre-order, in-order, or post-order."
No, these are standard ways of doing so, but nothing speaks against doing a reverse in-order (right branch, current, left branch), e.g. There are obviously 3! = 6 methods...  — Preceding unsigned comment added by 217.33.202.98 (talk) 00:36, 9 February 2016 (UTC)
thread_title:  Summary Depth-First wrong 

message: Hello fellow Wikipedians,
I have just modified  on Tree traversal. Please take a moment to review my edit. If you have any questions, or need the bot to ignore the links, or the page altogether, please visit this simple FaQ for additional information. I made the following changes:
*Added archive https://web.archive.org/web/20150213195803/http://www.math.ucla.edu:80/~wittman/10b.1.10w/Lectures/Lec18.pdf to http://www.math.ucla.edu/~wittman/10b.1.10w/Lectures/Lec18.pdf
*Added archive https://web.archive.org/web/20110606032941/http://dev.mysql.com/tech-resources/articles/hierarchical-data.html to http://dev.mysql.com/tech-resources/articles/hierarchical-data.html
When you have finished reviewing my changes, please set the checked parameter below to true or failed to let others know (documentation at ).
Cheers.—InternetArchiveBot (Report bug) 13:13, 10 November 2016 (UTC)
thread_title:  External links modified 

message: In the section "Infinite trees", the text says: "for example, the breadth-first search of the depth 2 tree above will take ?·2 steps: ? for the first level, and then another ? for the second level."
What does "?" mean here? And what does ":" mean in "?·2 steps: ?"? I have never met neither ":" nor "?" in mathematics before, so they should be explained and defined, at least with a wikilink to their apparently rather specialized meaning. --Jhertel (talk) 17:26, 17 April 2017 (UTC)
replies: text: Thanks, Alexei! --Jhertel (talk) 15:14, 13 June 2018 (UTC)
thread_title:  Question mark meaning what? 

message: Current implementation of iterative in-order traversal seems to be correct and looks beautiful by being so concise. Unfortunately there is one major flaw in it: current node is pushed onto the stack before the check if child is absent. It means, that all leaf nodes are pushed into the stack then immediately popped out.
My idea is quite simple - we all know that everything around is a trade-of: we trade speed for space, vise-versa, e.t.c.; where "pure" optimization is an elimination of unnecessary work/space... and given that we are talking about all the leaves here, the impact might be quite severe in some cases. Someone would argue that this implementation will benefit more in it's current state - as more comprehensible or maybe provided here for educational/introductory purposes only and not tied to optimization problem. But hit me if I'm wrong, this topic is so general, that this code will end up in many many projects around the globe. Arent' we are not just ruining the overall quality of the code, but also the coding hygiene of younger developers?
I run a couple of tests and achieved a speedup of 17%+ by just eliminating this unnecessary push/pop.
Checked some other places around, like geeksforgeeks, first 5 videos on youtube e.t.c. - and, man, this dirty code is all over the place!
Am I missing something?
Current implementation for the reference:
 iterativeInorder(node)
   s ← empty stack
   while (not s.isEmpty() or node ≠ null)
     if (node ≠ null)
       s.push(node)
       node ← node.left
     else
       node ← s.pop()
       visit(node)
       node ← node.right
Possible implementation - just to describe rough idea here (i.e. didn't check this exact implementation thoroughly, as mine is a bit more complicated for supporting ranges)
 s ← empty stack
 fillStack(node)
   while((child ← node.left) ≠ null)
     s.push(node);
     node ← child;
   return node
 iterativeInorder(node)
   node ← fillStack(node)
   while(true)
     visit(node);
     node ← node.right;
     if(node = null)
       if(s.isEmpty())
         return
       node ← stack.pop();
     else
       node ← fillStack(node)
DYefimov (talk) 01:59, 18 February 2020 (UTC)
replies: text: In my opinion the most interesting (tree) traversal is the 1-step-next traversal to the next in-order neighbour either right or left of the current node (=up or down). This also means that visit(node) is completely to the hand of the caller. Does somebody know a source of such an approach? --Nomen4Omen (talk) 16:16, 19 February 2020 (UTC)
thread_title:  Iterative Inorder Traversal Redux v2 

message: There are applications of this in computational geometry as well. For e.g. https://www.cs.princeton.edu/courses/archive/spr15/cos226/lectures/99GeometricSearch.pdf
Kgashok (talk) 13:13, 7 August 2020 (UTC)
thread_title:  Vertical or Orthogonal Traversal is missing 

message: All the current "iterative" traversal implementations use stacks, which makes them disguised recursive implementations.
Why were the actual iterative ones (the ones requiring that each node keep a pointer to its parents in addition to children) replaced with those?Medinoc (talk) 10:58, 8 November 2022 (UTC)
replies: text: Well I guess that isn't a full implementation. There was an implementation by Nomen4Omen that got deleted because it was unsourced; Nomen4Omen complained above but it doesn't seem to have been resolved. Mathnerd314159 (talk) 19:07, 8 November 2022 (UTC)
replies: text: Bu if there were a reliably sourced implementation using the parent pointer, I would say it would go in the threaded article, because this article really seems to assume that pointers only go down. Mathnerd314159 (talk) 19:30, 8 November 2022 (UTC)
thread_title:  What happened to the actually iterative traversal implementations?