剑指offer32.3-AcWing-45. 之字形打印二叉树
请实现一个函数按照之字形顺序从上向下打印二叉树。
即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]
8
/ \
12 2
/ \
6 4
输出:[[8], [2, 12], [6, 4]]
思路:
用两个变量分别记录当前层的节点个数以及下一层的节点个数。定义一个变量flag记录是从前往后打印链表还是从后向前打印链表。
C++ code:
/**
* 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>> printFromTopToBottom(TreeNode* root) {
if(root == NULL){
return {};
}
vector<vector<int>> res;
deque<TreeNode*> deque_node;
deque_node.push_back(root);
int now_layer_node = 1;
int next_layer_node = 0;
vector<int> now_layer_num;
res.push_back({root->val});
int flag = 1;
while(!deque_node.empty()){
if(flag == 1){
if(deque_node.back()->right){
now_layer_num.push_back(deque_node.back()->right->val);
deque_node.push_front(deque_node.back()->right);
next_layer_node++;
}
if(deque_node.back()->left){
now_layer_num.push_back(deque_node.back()->left->val);
deque_node.push_front(deque_node.back()->left);
next_layer_node++;
}
deque_node.pop_back();
}else{
if(deque_node.front()->left){
now_layer_num.push_back(deque_node.front()->left->val);
deque_node.push_back(deque_node.front()->left);
next_layer_node++;
}
if(deque_node.front()->right){
now_layer_num.push_back(deque_node.front()->right->val);
deque_node.push_back(deque_node.front()->right);
next_layer_node++;
}
deque_node.pop_front();
}
now_layer_node--;
if(now_layer_node == 0 && now_layer_num.size() != 0){
now_layer_node = next_layer_node;
next_layer_node = 0;
res.push_back(now_layer_num);
flag = 1 - flag;
now_layer_num.clear();
}
}
return res;
}
};
python code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def printFromTopToBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if root == None:
return []
res = []
now_res = []
q_node = []
res.append([root.val])
q_node.append(root)
now_layer_node = 1
next_layer_node = 0
flag = 1
while len(q_node):
if flag == 1:
if q_node[-1].right:
now_res.append(q_node[-1].right.val)
q_node.insert(0, q_node[-1].right)
next_layer_node += 1
if q_node[-1].left:
now_res.append(q_node[-1].left.val)
q_node.insert(0, q_node[-1].left)
next_layer_node += 1
q_node.remove(q_node[-1])
else:
if q_node[0].left:
now_res.append(q_node[0].left.val)
q_node.append(q_node[0].left)
next_layer_node += 1
if q_node[0].right:
now_res.append(q_node[0].right.val)
q_node.append(q_node[0].right)
next_layer_node += 1
q_node.remove(q_node[0])
now_layer_node -= 1
if now_layer_node == 0 and len(now_res) != 0:
now_layer_node = next_layer_node
next_layer_node = 0
res.append(now_res)
now_res = []
flag = 1 - flag
return res