Java solution by reverse the order of results getting from problem BINARY TREE LEVEL ORDER


  • 0
    D

    Actually, this problem is just a reverse problem of the original problem BINARY TREE LEVEL ORDER.
    below is the code.
    However, it gives us many interesting suggestions to enhance the problem.
    For example, we can come up with a new problem:

    Get the DIAGONAL ORDER OF A BINARY TREE.

    What I meant by "diagonal order" is that, suppose we have the following tree:
    The diagonal order list should be:
    enter image description here

    [
        [1, 2],
        [3, 4, 5],
        [6, 7],
        [8],
    ]
    

    However, this problem is easy to solve.
    Can you come up with more difficult problems?
    Welcome and let's explore ^_^

    public class Solution {
        public List<List<Integer>> levelOrderBottom(TreeNode root) {
            List<List<Integer>> results = new ArrayList<List<Integer>>();
            ArrayList<TreeNode> temp1 = new ArrayList<TreeNode>();
            ArrayList<TreeNode> temp2;
            TreeNode tempNode;
            if(root != null){
                temp1.add(root);
                while(temp1.size()>0){
                    ArrayList<Integer> list = new ArrayList<Integer>();
                    temp2 = new ArrayList<TreeNode>();
                    for(int i = 0; i<temp1.size(); i++) {
                        tempNode = temp1.get(i);
                        list.add(tempNode.val);
                        if(tempNode.left!=null) temp2.add(tempNode.left);
                        if(tempNode.right!=null) temp2.add(tempNode.right);
                    }
                    temp1 = temp2;
                    results.add(list);
                }
            }
            List<Integer> temp;
            int size = results.size();
            for(int i = 0; i < results.size()/2; i++) {
                temp = results.get(i);
                results.set(i, results.get(size-1-i));
                results.set(size-1-i, temp);
            }
            return results;
        }
    }
    

Log in to reply
 

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