Why it is wrong?


  • 0
    A

    import java.util.ArrayList;
    import java.util.List;
    import java.util.Stack;

    //入stack,然后出stack,判断node的深度来进行层次遍历.
    public class Binary_Tree_Level_Order_Traversal_II {
    public static List<List<Integer>> levelOrderBottom(TreeNode root) {

        List<List<Integer>> list = new ArrayList<List<Integer>>();
        List<Integer> nodeValue = new ArrayList<Integer>();
    
        Stack<TreeNode> stack =new Stack<TreeNode>();
    
    
        TreeNode  node = root;
    
    
        //入栈
        while (node!=null){
            stack.push(node);
    
            if (node.right!=null){
                stack.push(node.right);
                node=node.right;
            }
            if (node.left!=null){
                stack.push(node.left);
                node=node.left;
            }
        }
    
        //根据深度出栈,深度相同的一起出栈,并放在一个list里
        while (!stack.isEmpty()){
            TreeNode node1;
            node1 = stack.pop();
            nodeValue.add(node1.val);
            while (depth(stack.peek()) == depth(node1)){
                nodeValue.add(stack.peek().val);
                list.add(nodeValue);
              // stack.pop();
            }
            while (depth(stack.peek()) != depth(node1)){
    
                nodeValue = new ArrayList<>();
                nodeValue.add(stack.peek().val);
                list.add(nodeValue);
    
            }
    
        }
    
    
        return list;
    
    }
    
    public static int depth(TreeNode node){
    
        if (node == null) return 0;
    
        return Math.max(depth(node.left),depth(node.right))+1;
    }
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }
    
    public static void main(String[] args) {
        TreeNode a = new TreeNode(5);
        TreeNode b = new TreeNode(4);
        TreeNode c = new TreeNode(7);
        TreeNode d = new TreeNode(2);
        TreeNode e = new TreeNode(3);
        TreeNode f = new TreeNode(6);
        TreeNode g = new TreeNode(8);
    
        a.left = b;
        a.right = c;
        b.left = d;
        b.right = e;
        c.left = f;
        d.right = g;
    
        List<List<Integer>> list = levelOrderBottom(a);
    
        for (List<Integer> list1 : list){
            for (Integer i : list1){
                System.out.print(i.toString()+" ");
    
            }
            System.out.println();
        }
    
    }
    

    }


  • 0

    The Solutions to be coded on this OJ(Online Judge) are just method - only submissions . You don't need to write main method etc . Just complete the method given to you and create other helper methods if at all you require them .Then , run your code . If you feel its correct , submit your code and check the results.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.