zoukankan      html  css  js  c++  java
  • [LeetCode] 314. Binary Tree Vertical Order Traversal 二叉树的垂直遍历

    Given a binary tree, return the vertical order traversal of its nodes' values. (ie, from top to bottom, column by column).

    If two nodes are in the same row and column, the order should be from left to right.

    Examples:
    Given binary tree [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    return its vertical order traversal as:

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

    Given binary tree [3,9,20,4,5,2,7],

        _3_
       /   
      9    20
     /    / 
    4   5 2   7
    

    return its vertical order traversal as:

    [
      [4],
      [9],
      [3,5,2],
      [20],
      [7]
    ]

    二叉树的垂直遍历。

    解法:如果一个node的column是 i,那么它的左子树column就是i - 1,右子树column就是i + 1。建立一个TreeColumnNode,包含一个TreeNode,以及一个column value,然后用level order traversal进行计算,并用一个HashMap保存column value以及相同value的点。也要设置一个min column value和一个max column value,方便最后按照从小到大顺序获取hashmap里的值输出。

    Java: 

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        private class TreeColumnNode{
            public TreeNode treeNode;
            int col;
            public TreeColumnNode(TreeNode node, int col) {
                this.treeNode = node;
                this.col = col;
            }
        }
        
        public List<List<Integer>> verticalOrder(TreeNode root) {    
            List<List<Integer>> res = new ArrayList<>();
            if(root == null) {
                return res;
            }
            Queue<TreeColumnNode> queue = new LinkedList<>();
            Map<Integer, List<Integer>> map = new HashMap<>();
            queue.offer(new TreeColumnNode(root, 0));
            int curLevel = 1;
            int nextLevel = 0;
            int min = 0;
            int max = 0;
            
            while(!queue.isEmpty()) {
                TreeColumnNode node = queue.poll();
                if(map.containsKey(node.col)) {
                    map.get(node.col).add(node.treeNode.val);
                } else {
                    map.put(node.col, new ArrayList<Integer>(Arrays.asList(node.treeNode.val)));
                }
                curLevel--;
                
                if(node.treeNode.left != null) {
                    queue.offer(new TreeColumnNode(node.treeNode.left, node.col - 1));
                    nextLevel++;
                    min = Math.min(node.col - 1, min);
                }
                if(node.treeNode.right != null) {
                    queue.offer(new TreeColumnNode(node.treeNode.right, node.col + 1));
                    nextLevel++;
                    max = Math.max(node.col + 1, max);
                }
                if(curLevel == 0) {
                    curLevel = nextLevel;
                    nextLevel = 0;
                }
            }
            
            for(int i = min; i <= max; i++) {
                res.add(map.get(i));
            }
            
            return res;
        }
    }
    

    Java:

    class Solution {
        public List<List<Integer>> verticalOrder(TreeNode root) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(root==null)
                return result;
    
            // level and list    
            HashMap<Integer, ArrayList<Integer>> map = new HashMap<Integer, ArrayList<Integer>>();
    
            LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
            LinkedList<Integer> level = new LinkedList<Integer>();
    
            queue.offer(root);
            level.offer(0);
    
            int minLevel=0;
            int maxLevel=0;
    
            while(!queue.isEmpty()){
                TreeNode p = queue.poll();
                int l = level.poll();
    
                //track min and max levels
                minLevel=Math.min(minLevel, l);
                maxLevel=Math.max(maxLevel, l);
    
                if(map.containsKey(l)){
                    map.get(l).add(p.val);
                }else{
                    ArrayList<Integer> list = new ArrayList<Integer>();
                    list.add(p.val);
                    map.put(l, list);
                }
    
                if(p.left!=null){
                    queue.offer(p.left);
                    level.offer(l-1);
                }
    
                if(p.right!=null){
                    queue.offer(p.right);
                    level.offer(l+1);
                }
            }
    
    
            for(int i=minLevel; i<=maxLevel; i++){
                if(map.containsKey(i)){
                    result.add(map.get(i));
                }
            }
    
            return result;
        }
    }
    

    Python:  BFS + hash solution.

    class Solution(object):
        def verticalOrder(self, root):
            """
            :type root: TreeNode
            :rtype: List[List[int]]
            """
            cols = collections.defaultdict(list)
            queue = [(root, 0)]
            for node, i in queue:
                if node:
                    cols[i].append(node.val)
                    queue += (node.left, i - 1), (node.right, i + 1)
            return [cols[i] for i in xrange(min(cols.keys()), max(cols.keys()) + 1)] 
                       if cols else []
    

    C++:

    class Solution {
    public:
        vector<vector<int>> verticalOrder(TreeNode* root) {
            vector<vector<int>> res;
            if (!root) return res;
            map<int, vector<int>> m;
            queue<pair<int, TreeNode*>> q;
            q.push({0, root});
            while (!q.empty()) {
                auto a = q.front(); q.pop();
                m[a.first].push_back(a.second->val);
                if (a.second->left) q.push({a.first - 1, a.second->left});
                if (a.second->right) q.push({a.first + 1, a.second->right});
            }
            for (auto a : m) {
                res.push_back(a.second);
            }
            return res;
        }
    };
    
    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<vector<int>> verticalOrder(TreeNode* root) {
            unordered_map<int, vector<int>> cols;
            vector<pair<TreeNode *, int>> queue{{root, 0}};
            for (int i = 0; i < queue.size(); ++i) {
                TreeNode *node;
                int j;
                tie(node, j) = queue[i];
                if (node) {
                    cols[j].emplace_back(node->val);
                    queue.push_back({node->left, j - 1});
                    queue.push_back({node->right, j + 1});
                }
            }
            int min_idx = numeric_limits<int>::max(), 
                max_idx = numeric_limits<int>::min();
            for (const auto& kvp : cols) {
                min_idx = min(min_idx, kvp.first);
                max_idx = max(max_idx, kvp.first);
            }
            vector<vector<int>> res;
            for (int i = min_idx; !cols.empty() && i <= max_idx; ++i) {
                res.emplace_back(move(cols[i]));
            }
            return res;
        }
    };

      

    All LeetCode Questions List 题目汇总

  • 相关阅读:
    聊聊算法——回溯算法
    Redis高级用法
    聊聊算法——BFS和DFS
    这就是Java代码生成器的制作流程
    Spring Boot 2 实战:常用读取配置的方式
    Spring Security 实战干货:图解Spring Security中的Servlet过滤器体系
    想做时间管理大师?你可以试试Mybatis Plus代码生成器
    Maven中央仓库正式成为Oracle官方JDBC驱动程序组件分发中心
    作为一个Java开发你用过Jib吗
    使用反应式关系数据库连接规范R2DBC操作MySQL数据库
  • 原文地址:https://www.cnblogs.com/lightwindy/p/8661594.html
Copyright © 2011-2022 走看看