leetcode 103. 二叉树的锯齿形层次遍历(C++、python)

给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。

例如:
给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回锯齿形层次遍历如下:

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

C++

/**
 * 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:
    void dfs(TreeNode* root, map<int,vector<int>>& tmp, int num)
    {
        if(root)
        {
            tmp[num].push_back(root->val);
            dfs(root->left,tmp,num+1);
            dfs(root->right,tmp,num+1);
        }
    }
    
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) 
    {
        vector<vector<int>> res;
        map<int,vector<int>> tmp;
        dfs(root,tmp,0);
        for(auto it:tmp)
        {
            if(0==it.first%2)
            {
                res.push_back(it.second);
            }
            else
            {
                reverse(it.second.begin(),it.second.end());
                res.push_back(it.second);
            }
        }
        return res;
    }
};

python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def dfs(self,root,dic,num):
        if root:
            if num in dic:
                dic[num].append(root.val)
            else:
                dic[num]=[root.val]
            self.dfs(root.left,dic,num+1)
            self.dfs(root.right,dic,num+1)
                
    
    def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
        res=[]
        dic={}
        self.dfs(root,dic,0)
        for key in dic:
            if 0==key%2:
                res+=[dic[key]]
            else:
                dic[key].reverse()
                res+=[dic[key]]
        return res

猜你喜欢

转载自blog.csdn.net/qq_27060423/article/details/93201182