zoukankan      html  css  js  c++  java
  • 【LeetCode】Binary Tree Level Order Traversal II

    Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).

    For example:
    Given binary tree {3,9,20,#,#,15,7},

        3
       / 
      9  20
        /  
       15   7
    

    return its bottom-up level order traversal as:

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

    http://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/
    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ArrayList<ArrayList<Integer>> levelOrderBottom(TreeNode root) {
            ArrayList<Integer> temp =new ArrayList<Integer>();
            Stack<ArrayList<Integer>> stack = new Stack<ArrayList<Integer>>();
            ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
            Queue<TreeNode> tempqueue = new LinkedList<TreeNode>();
            Queue<TreeNode> queue = new LinkedList<TreeNode>();
            if(root!=null){
                queue.offer(root);
    
                while(root!=null){
                    temp.add(root.val);
                    if(root.left!=null){
                        tempqueue.offer(root.left);
                    }
                    if(root.right!=null){
                        tempqueue.offer(root.right);
                    }
                    
                    queue.poll();
                    if(queue.size()==0){
                        queue=tempqueue;
                        tempqueue= new LinkedList<TreeNode>();
                        stack.push(temp);
                        temp=new ArrayList<Integer>();
                        root=queue.peek();
                    }else{
                        root = queue.peek();
                    }
                }
                while(!stack.isEmpty()){
                    re.add(stack.peek());
                    stack.pop();
                }
                
                return re;
            }else{
                return re;
            }        
            
            
        }
    }
  • 相关阅读:
    算法(一)—— 河内之塔(汉诺塔)
    JAVA爬取网页邮箱
    js中判断某字符串含有某字符出现的次数
    逻辑删除和物理删除的区别
    Forward和Redirect的区别
    Postman 传Map类型的参数
    Java基础
    【html-css】
    【HTML----】
    【python-while-以及字符串的相关操作和函数】
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3714785.html
Copyright © 2011-2022 走看看