The sequence traversal of binary tree

Source: Internet
Author: User

Topic Description: Give a binary tree, return to its node value of the first sequence traversal. Request cannot be recursive.

What is the sequence traversal should have been very clear, the example I have omitted.


About the binary tree of the first traversal, I have already explained in detail, at that time is the simplest recursive solution to this problem, see: Click on the Open link, but recursion is a natural flaw, that is inefficient. So someone is trying to replace recursion with a more efficient approach. In this case, because the binary tree in the first sequence traversal is a "deep search" strategy (in-sequence traversal, subsequent traversal are also "deep search"), and "deep search" in fact, the general situation can be implemented with the stack.

Recall that the first sequence traversal is a "root-left-right" process


Take this picture above, the result of the forward traversal should be: abdecfg, for each node that arrives, scan the node itself first, then scan the left child, the last right child's process. So I might as well build such a stack--stack

1. Stack stores the current node, at first, of course, the root node A,stack = [A]

2. Delete stack top element, add the value stored by the top of the stack to the final list of results we want

3. If the deleted element has the right child, will the right child join Stack,stack = [C]

4. If the deleted element has left child, will the left child join Stack,stack = [C,b]

As you can see, since the right child joins first, the new stack is iterated from the first step, the left child is processed first (b), and so on, and so on, the left child is removed (b), and then the right child of the node (b) is added: Stack = [C,e], Finally add left child: Stack = [C,e,d] ...

Obviously, I'm here. The deep search strategy is realized through the special structure of the stack.

Look at the code:

"" "
Definition of TreeNode:
class TreeNode:
    def __init__ (Self, val):
        self.val = val
        self.left, Self.right = none, none
"" "


class Solution:" ""
    @param root:the root of binary tree.
    @return: Preorder in ArrayList which contains node values.
    "" " def preordertraversal (self, root): Result
        = []
        stack = []
        # can also be written as if root:
        if root!= None:
            stack. Append (root) while
        len (stack)!= 0:
            cur = stack.pop ()
            result.append (cur.val)
            if Cur.right None:
                stack.append (cur.right)
            if Cur.left!= None:
                stack.append (cur.left) return result
        # Write Your code here


Note that the concise wording of line 19th can be as if root:,24,26, but I am now making it easier for everyone to understand.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.