zoukankan      html  css  js  c++  java
  • 按之字形顺序打印二叉树

    按之字形顺序打印二叉树

    题目描述

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

    思路

    1. 根据题意,每行的节点的访问顺序是相反的,我们可以用两个栈来隔行存储,一个栈中根据“左结点->右结点”的顺序访问另一个栈的栈顶元素,而另一个栈根据“右子树->左子树”的顺序访问另一个栈的栈顶元素,直到两个栈都为空

    代码

    import java.util.ArrayList;
    import java.util.Stack;
    /*
    public class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
    
        public TreeNode(int val) {
            this.val = val;
    
        }
    
    }
    */
    public class Solution {
        public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
    		ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
            if (pRoot == null) {
                return result;
            }
            Stack<TreeNode> stack1 = new Stack<TreeNode>();
            Stack<TreeNode> stack2 = new Stack<TreeNode>();
            ArrayList<Integer> list = new ArrayList<Integer>();
            list.add(pRoot.val);
            result.add(list);
            stack1.push(pRoot);
            while (stack1.isEmpty() || stack2.isEmpty()) {
                if (stack1.isEmpty() && stack2.isEmpty()) {
                    break;
                }
                ArrayList<Integer> temp = new ArrayList<Integer>();
                if (stack2.isEmpty()) {
                    while (!stack1.isEmpty()) {
                        if (stack1.peek().right != null) {
                            temp.add(stack1.peek().right.val);
                            stack2.push(stack1.peek().right);
                        }
                        if (stack1.peek().left != null) {
                            temp.add(stack1.peek().left.val);
                            stack2.push(stack1.peek().left);
                        }
                        stack1.pop();
                    }
                } else {
                    while (!stack2.isEmpty()) {
                        if (stack2.peek().left != null) {
                            temp.add(stack2.peek().left.val);
                            stack1.push(stack2.peek().left);
                        }
                        if (stack2.peek().right != null) {
                            temp.add(stack2.peek().right.val);
                            stack1.push(stack2.peek().right);
                        }
                        stack2.pop();
                    }
                }
                if (temp.size() > 0) {
                    result.add(temp);
                }
            }
            return result;
        }
    
    }
  • 相关阅读:
    JS替换字符
    sql 两个表字段叠加
    Qt实现窗口半透明显示
    Qt 设置窗口属性setWindowFlags函数
    ARM-Linux按键和旋钮控制
    飞凌开发板OK335xD烧写Linux镜像总结
    Qt QGraphics类应用——图片移动+选点缩放+控制移动区域
    Qt QGraphics类应用——地图缩放选点
    Ubuntu 同时使用有线和无线(有线连开发板,无限上网)
    Qt 自定义控件提升,头文件找不到的问题
  • 原文地址:https://www.cnblogs.com/nickup/p/9806609.html
Copyright © 2011-2022 走看看