[LeetCode] 103. Binary Tree Zigzag Level Order Traversal Java

來源:互聯網
上載者:User

標籤:solution   add   分析   stack   return   根據   rsa   des   res   

題目:

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,null,null,15,7],

    3   /   9  20    /     15   7

return its zigzag level order traversal as:

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

題意及分析:給出一個橫向遍曆的二叉樹,要求給出 按照Z字形橫向遍曆的每一層 的點。這道題我們可以用stack來求解,簡單來講就是把每一層添加到一個stack裡面,然後遍曆輸出結果的同時將遍曆點的子節點添加到一個新的stack裡面(先添加左子節點還是右子節點根據上一層添加的順序),遍曆完之後將新的stack賦值給stack進行下一層的遍曆。代碼如下:

代碼:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {        List<List<Integer>> res=new ArrayList<>();  TreeNode node=root; Stack<TreeNode> stack =new Stack<>(); if(node!=null) stack.push(node); int leftOrRight=0;//0為先遍曆左子樹,1為右子樹 while(!stack.isEmpty()){ Stack<TreeNode> nextStack =new Stack<>(); List<Integer> list=new ArrayList<>(); while(!stack.isEmpty()){ TreeNode temp=stack.pop(); list.add(temp.val); if(leftOrRight==0){ if(temp.left!=null) nextStack.push(temp.left); if(temp.right!=null) nextStack.push(temp.right); }else{ if(temp.right!=null) nextStack.push(temp.right); if(temp.left!=null) nextStack.push(temp.left); } } if(leftOrRight==0) leftOrRight=1; else {leftOrRight=0;} res.add(new ArrayList<>(list)); //System.out.println(list); list.clear(); stack=(Stack<TreeNode>) nextStack.clone ();; nextStack.clear(); } return res;    }}

 

  

 

[LeetCode] 103. Binary Tree Zigzag Level Order Traversal Java

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.