leetcode Binary Tree Zigzag Level Order Traversal

本文介绍了一种实现二叉树锯齿形层序遍历的方法,使用队列与栈交替存储每层节点值来达到从左到右再从右到左的打印效果。

题目链接

思路:
简单思路

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {




        LinkedList<TreeNode> queue=new LinkedList<TreeNode>();
        Stack<Integer> stack=new Stack<Integer>();
        LinkedList<List<Integer>> result=new LinkedList<List<Integer>>();
        LinkedList<Integer> row=new LinkedList<Integer>();
        boolean useStack=false;
        if(root==null)
        {
            return result;
        }

        queue.add(root);
        queue.add(null);

        while(queue.size()>0)
        {
            TreeNode temp=queue.pop();
            if(temp==null)
            {
                if(useStack)
                {

                    while(!stack.empty())
                    {
                        row.add(stack.pop());
                    }
                }
                result.add(row);
                row=new LinkedList<Integer>();
                useStack=!useStack;
                if(queue.size()>0)
                {
                    queue.add(null);
                    continue;
                }
                else
                {
                    break;
                }
            }   

            if(useStack)
            {
                stack.add(temp.val);
            }
            else
            {
                row.add(temp.val);
            }
            if(temp.left!=null)
            {
                queue.add(temp.left);
            }
            if(temp.right!=null)
            {
                queue.add(temp.right);
            }
        }
        return result;
    }
}
### Z字形遍历(Zigzag Traversal)的概念 二叉树的Z字形遍历是一种特殊的层序遍历方式,在这种遍历中,每一层节点按照不同的方向访问。奇数层从左到右访问,偶数层则从右到左访问[^1]。 --- ### 实现思路 为了实现Z字形遍历,可以利用两个栈来分别存储当前层和下一层的节点。通过交替操作这两个栈,可以在不改变原有树结构的情况下完成Z字形遍历。具体方法如下: - 使用一个标志变量 `left_to_right` 来控制每层的方向。 - 当前层的节点按指定方向弹出并处理,同时将其子节点按相反顺序压入下一个栈中。 - 完成当前层后切换方向继续处理下一层次。 这种方法的时间复杂度为 O(n),其中 n 是树中的节点总数,因为每个节点仅被访问一次。 --- ### Zigzag 遍历的 C 语言实现 以下是基于上述逻辑编写的 C 语言代码示例: ```c #include <stdio.h> #include <stdlib.h> // 定义二叉树节点结构体 typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; // 创建新节点函数 TreeNode* createNode(int value) { TreeNode* newNode = (TreeNode*)malloc(sizeof(TreeNode)); newNode->val = value; newNode->left = NULL; newNode->right = NULL; return newNode; } void zigzagTraversal(TreeNode* root) { if (!root) return; // 如果根为空,则直接返回 // 初始化两个栈 typedef struct Stack { TreeNode** array; int top; int capacity; } Stack; Stack* stack1 = (Stack*)malloc(sizeof(Stack)); Stack* stack2 = (Stack*)malloc(sizeof(Stack)); stack1->capacity = stack2->capacity = 100; // 假设最大容量为100 stack1->array = (TreeNode**)malloc(stack1->capacity * sizeof(TreeNode*)); stack2->array = (TreeNode**)malloc(stack2->capacity * sizeof(TreeNode*)); stack1->top = stack2->top = -1; // 将根节点推入第一个栈 stack1->array[++stack1->top] = root; int leftToRight = 1; // 方向标记:1 表示从左到右,0 表示从右到左 while (stack1->top != -1 || stack2->top != -1) { if (leftToRight) { // 处理 stack1 中的节点 while (stack1->top != -1) { TreeNode* node = stack1->array[stack1->top--]; printf("%d ", node->val); if (node->left) stack2->array[++stack2->top] = node->left; if (node->right) stack2->array[++stack2->top] = node->right; } } else { // 处理 stack2 中的节点 while (stack2->top != -1) { TreeNode* node = stack2->array[stack2->top--]; printf("%d ", node->val); if (node->right) stack1->array[++stack1->top] = node->right; if (node->left) stack1->array[++stack1->top] = node->left; } } // 切换方向 leftToRight = !leftToRight; } } int main() { // 构建一棵简单的二叉树作为测试数据 TreeNode* root = createNode(1); root->left = createNode(2); root->right = createNode(3); root->left->left = createNode(4); root->left->right = createNode(5); root->right->left = createNode(6); root->right->right = createNode(7); printf("Zigzag Traversal of Binary Tree:\n"); zigzagTraversal(root); // 调用zigzagTraversal函数打印结果 return 0; } ``` --- ### 输出解释 对于上面构建的二叉树,其结构如下所示: ``` 1 / \ 2 3 / \ / \ 4 5 6 7 ``` 执行程序后的输出将是: ``` Zigzag Traversal of Binary Tree: 1 3 2 4 5 6 7 ``` 这表明第一层从左至右读取,第二层从右往左读取,依此类推。 --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值