Leetcode 103.Binary tree Zigzag Level order traversal (binary tree Z-shape horizontal order) thinking and method of solving problems

Source: Internet
Author: User

Given a binary tree, return 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    /   7

Return its zigzag level order traversal as:

[  3],  [20,9],  [15,7]]

Train of thought: With two fork tree horizontal sequence problem-solving idea is similar, get the horizontal order result, then dual number chain list inversion can. ‘


The code is as follows:

/** * Definition for a binary tree node.  * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *}    */public class Solution {list<list<integer>> List = new arraylist<list<integer>> ();        Public list<list<integer>> Zigzaglevelorder (TreeNode root) {DFS (0,root);        Exchange order every 1 lines for (int i = 1; i < list.size (); i = i+2) {list<integer> Al = List.get (i);        int len = Al.size ();        Reverse exchange for (int j = 0; J + J < Len-1; J + +) {int k = Al.get (j);        Al.set (J, Al.get (Len-1-j));        Al.set (Len-1-j, k);    }} return list; }/** * Sequence traversal, add list * @param the depth of the DEP tree based on depth * @param root root node */private void Dfs (int dep,treenode roo        T) {if (root = null) {return;        } list<integer> al;//Get Al value if (list.size () > Dep) {al = List.get (DEP) as appropriate;  }else{          Al = new arraylist<integer> ();        List.add (AL);        } dfs (Dep+1,root.left);        Al.add (Root.val);    DFS (Dep+1,root.right); }}



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Leetcode 103.Binary tree Zigzag Level order traversal (binary tree Z-shape horizontal order) thinking and method of solving problems

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.