• 之字形层次遍历二叉树


    之字形层次遍历二叉树:层次遍历二叉树,并且奇数行为从左到右(根节点为第一层),偶数行为从右到左。
    先写一个容易实现的,参照《编程之美》3.10分层遍历二叉树的做法,先编写一个用来处理制定层的函数,然后逐层调用这个函数即可。

    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).
    For example:
    Given binary tree{3,9,20,#,#,15,7},
    3
    /
    9 20
    /
    15 7

    return its zigzag level order traversal as:
    [
    [3],
    [20,9],
    [15,7]
    ]

    confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.

    OJ's Binary Tree Serialization:
    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
    Here's an example:
    1
    /
    2 3
    /
    4

    5
    The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    
    
    class Solution {
    public:
    	vector<vector<int> > zigzagLevelOrder(TreeNode* root){
    		vector<vector<int> >result;
    		for (int level = 0;; level++){
    			vector<int> q = ZigzagNodeAtLevel(root, level);
    			if (q.size() == 0){
    				break;
    			}
    			result.push_back(q);
    		}
            return result;
    	}
    
    	vector<int> ZigzagNodeAtLevel(TreeNode* root, int level){
    		vector<int> res;
    		if (!root || level<0){
    			return res;
    		}
    		if (level == 0){
    			res.push_back(root->val);
    		}
    		// return PrintNodeAtLevel(root->left, level - 1) + PrintNodeAtLevel(root->right, level - 1);
    		vector<int> left_res = ZigzagNodeAtLevel(root->left, level - 1);
    		vector<int> right_res = ZigzagNodeAtLevel(root->right, level - 1);
            
            if(level%2==1){
                for (int i = right_res.size()-1; i>=0; i--){
                    res.push_back(right_res[i]);
                }
                for (int i = left_res.size()-1; i >=0; i--){
                    res.push_back(left_res[i]);
                }
    
            }else{
                for (int i = left_res.size()-1; i >=0; i--){
                    res.push_back(left_res[i]);
                }
                for (int i = right_res.size()-1; i>=0; i--){
                    res.push_back(right_res[i]);
                }
            }
    		
    		return res;
    	}
    };
    
  • 相关阅读:
    构建高性能的读服务
    Redis基础入门
    基于TCP实现简单的聊天室
    递归

    Go标准库Cond
    排序(冒泡,选择,插入,快速)
    链表
    队列
    Golang实现RPC
  • 原文地址:https://www.cnblogs.com/zjutzz/p/6493284.html
Copyright © 2020-2023  润新知