[LeetCode]第十八题 :遍历树

题目描述:

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

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

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

题目解释:

给出一个二叉树,返回自底向上的遍历(从左到右、从下到上)

题目解法:

1.我的解法(目前仍有错误)。大致思路如下,题目要求是层次遍历、自左向右,还要求每个树的子节点在同一个数组内。要保证层次遍历,需要借助一个队列,这个队列的处理逻辑是先将根节点加入到队列中,然后父节点出队,父节点出队时将其子节点加入到队列中。自左向右的处理逻辑就是先加入左子树后加入右子树。每个树的子节点在同一数组内的处理逻辑是不遍历叶子结点,只遍历非叶子结点,将非叶子结点的左右子树加入到同一数组内(这样的话无法遍历到根节点,需要提前加入根节点)。在官方的网站上这段代码遇到[1,2,3,4,null,null,5]时答案错误,但是我没发现错误在哪里。代码入下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        LinkedList<TreeNode> linkedList = new LinkedList<>();
        LinkedList<List<Integer>> list = new LinkedList<>();
        if(root == null) return list;
        linkedList.add(root);
        List<Integer> node = new ArrayList();
        node.add(root.val);
        list.addFirst(node);
        while(!linkedList.isEmpty()) {
            TreeNode temp = linkedList.poll();
            node = new ArrayList();
            if(temp.left != null || temp.right != null) {
                if(temp.left != null) {
                    linkedList.add(temp.left);
                    node.add(temp.left.val);
                }
                if(temp.right != null) {
                    linkedList.add(temp.right);
                    node.add(temp.right.val);
                }
                list.addFirst(node);
            }
        }
        return list;
    }
}
2.讨论区的解法:也是借助一个队列,然后建一个结果list,先把根节点加入到队列中,当队列不为空的时候进行处理。(这里我就看不懂了,为什么levelNum = queue.size()?)这个levelNum应该是指这一层的节点的数量,道理上和我的思路差不都,以[1,2,3,4,null,null,5]举例,在去掉2和3之后,队列中应该是包含4和5,这时levelNum应该是等于2,总之是想不明白……
class Solution {
     public List<List<Integer>> levelOrderBottom(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        List<List<Integer>> wrapList = new LinkedList<List<Integer>>();
        
        if(root == null) return wrapList;
        
        queue.offer(root);
        while(!queue.isEmpty()){
            int levelNum = queue.size();
            List<Integer> subList = new LinkedList<Integer>();
            for(int i=0; i<levelNum; i++) {
                if(queue.peek().left != null) queue.offer(queue.peek().left);
                if(queue.peek().right != null) queue.offer(queue.peek().right);
                subList.add(queue.poll().val);
            }
            wrapList.add(0, subList);
        }
        return wrapList;
    }
}

猜你喜欢

转载自blog.csdn.net/woaily1346/article/details/80907498