Leetcode: Binary tree zigzag level order Traversal_leetcode

Source: Internet
Author: User

Given a binary tree and return to the zigzag level order traversal of its nodes ' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary Tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
Return it zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]

Sequence traversal of binary trees in this way zigzag

Solution: Through the topic requirements we can know that the current traversal layer as the base, the way to traverse is from left to right, or from right to left. Then we are traversing the process as long as the current layer to determine the traversal of the elements into the storage structure of the insertion mode can be, from left to right to insert the normal, vice versa is inserted. The rest is the normal sequence traversal.

Code:

 public class Solution {public list<list<integer>> zigzaglevelorder (TreeNode root) {list<
        list<integer>> result = new arraylist<list<integer>> ();
        Travel (result, root, 0);
    return result;
            private void Travel (list<list<integer>> result, TreeNode root, int level) {if (root = null) {
        Return
            } if (Result.size () <= level) {list<integer> next = new linkedlist<> ();
        Result.add (next);
        list<integer> temp = Result.get (level);
        if (level% 2 = 0) {temp.add (root.val);
        } else{temp.add (0, Root.val);
        Travel (result, root.left, level + 1);
    Travel (result, root.right, level + 1); }
}

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.