【二叉树】【BFS】剑指offer——面试题61:按之字形顺序打印二叉树

力扣

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def decorateRecord(self, root: Optional[TreeNode]) -> List[List[int]]:
        if not root:
            return []
        res = list()
        q = collections.deque()
        q.append(root)
        tag = 0
        while q:
            cur_size = len(q)
            tmp = list()
            for i in range(cur_size):
                cur_node = q.popleft()
                tmp.append(cur_node.val)
                if cur_node.left:
                    q.append(cur_node.left)
                if cur_node.right:
                    q.append(cur_node.right)
            if tag % 2 == 1:
                tmp.reverse()
            res.append(tmp.copy())
            tag = (tag + 1) % 2
        
        return res 

Java

class Solution {
    public List<List<Integer>> decorateRecord(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        int layer = 1;
        List<Integer> tmp = new ArrayList<>();
        Queue<TreeNode> queue1 = new LinkedList<>();
        Queue<TreeNode> queue2 = new LinkedList<>();
        queue1.offer(root);
        while (!queue1.isEmpty()) {
            TreeNode topNode = queue1.poll();
            if (layer % 2 == 0) { // 偶数层从前往后插入元素!!!
                tmp.add(0, topNode.val);
            } else {
                tmp.add(topNode.val);
            }
            if (topNode.left != null) {
                queue2.offer(topNode.left);
            }
            if (topNode.right != null) {
                queue2.offer(topNode.right);
            }
        
            if (queue1.isEmpty()) {
                res.add(new ArrayList<>(tmp));
                tmp.clear();
                ++layer;
                queue1 = new LinkedList<>(queue2);
                queue2.clear();
            }
        }

        return res;
    }
}

class Solution {
    public List<List<Integer>> decorateRecord(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (Objects.isNull(root)) {
            return res;
        }
        List<TreeNode> list1 = new LinkedList<>();
        List<TreeNode> list2 = new LinkedList<>();
        List<Integer> valList = new ArrayList<>();
        list1.add(root);
        int count = 1;
        while (list1.size() > 0) {
            TreeNode topNode = list1.remove(0);
            valList.add(topNode.val);
            if (!Objects.isNull(topNode.left)) {
                list2.add(topNode.left);
            }
            if (!Objects.isNull(topNode.right)) {
                list2.add(topNode.right);
            }
            if (list1.size() == 0) {
                if (count % 2 == 0) {
                    Collections.reverse(valList);
                }
                res.add(new ArrayList<>(valList));
                valList.clear();
                list1 = new LinkedList<>(list2);
                list2.clear();

                ++count;
            }
        }

        return res;
    }
}

#剑指offer——面试题61:按之字形顺序打印二叉树
##Solution1:
基于上一题的解法,缺点:效率低下!

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if(pRoot == NULL)
            return res;
        vector<int> temp;
        int symbol = 1, cur = 1, next = 0;//若symbol%2 == 1,则是奇数行;否则是偶数行
        queue<struct TreeNode*> queue_tree;
        queue_tree.push(pRoot);
        while(!queue_tree.empty()) {
            temp.push_back(queue_tree.front()->val);
            cur--;
            if(queue_tree.front()->left != NULL) {
                queue_tree.push(queue_tree.front()->left);
                next++;
            }
            if(queue_tree.front()->right != NULL) {
                queue_tree.push(queue_tree.front()->right);
                next++;
            }
            if(cur == 0) {
                if(symbol%2 == 1) 
                    res.push_back(temp);
                else {
                    vec_swap(temp);
                    res.push_back(temp);
                }
                temp.clear();
                cur = next;
                next = 0;
                symbol++;
            }
            queue_tree.pop();
        }
        return res;
    }
    
    void vec_swap(vector<int> &temp) {
        int i = 0, j = temp.size() - 1, temp_val = 0;
        while(i < j) {
            temp_val = temp[i];
            temp[i] = temp[j];
            temp[j] = temp_val;
            i++;
            j--;
        }
        return;
    }
    
};

##Solution2:
书上的思路,用了两个栈结构来存储数据,复杂度为 O ( n ) O(n) O(n),更好的算法。学习之

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
*/
class Solution {
public:
    vector<vector<int> > Print(TreeNode* pRoot) {
        vector<vector<int> > res;
        if(pRoot == NULL)
            return res;
        vector<int> temp;
        stack<struct TreeNode* > stack_node[2];//栈数组,数组的每个元素均是栈,栈的数据类型是TreeNode*
        int cur = 0, next = 1;
        stack_node[cur].push(pRoot);
        while(!stack_node[0].empty() || !stack_node[1].empty()) {
            temp.push_back(stack_node[cur].top()->val);
            if(cur == 0) {
                if(stack_node[cur].top()->left != NULL)
                    stack_node[next].push(stack_node[cur].top()->left);
                if(stack_node[cur].top()->right != NULL)
                    stack_node[next].push(stack_node[cur].top()->right);
            }
            else {
                if(stack_node[cur].top()->right != NULL)
                    stack_node[next].push(stack_node[cur].top()->right);
                if(stack_node[cur].top()->left != NULL)
                    stack_node[next].push(stack_node[cur].top()->left);
            }
            stack_node[cur].pop();
            if(stack_node[cur].empty()) {
                res.push_back(temp);
                temp.clear();
                cur = 1 - cur;
                next = 1 - next;
            }
        }
        return res;
    }
};
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值