zoukankan      html  css  js  c++  java
  • 非递归遍历二叉树

    public class Solution {
    
    
        public static void main(String[] args) {}
    
        public List<Integer> preOrderTravel(TreeNode root) {
            List<Integer> result = new ArrayList<>();
    
            if(root == null) {
                return result;
            }
    
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
    
            while(!stack.isEmpty()) {
                TreeNode current = stack.pop();
    
                result.add(current.val);
    
                if(current.right != null) {
                    stack.push(current.right);
                }
    
                if(current.left != null) {
                    stack.push(current.left);
                }
            }
    
            return result;
        }
    
        public List<Integer> inOrderTravel(TreeNode root) {
            List<Integer> result = new ArrayList<>();
    
            if(root == null) {
                return result;
            }
    
            Stack<TreeNode> stack = new Stack<>();
    
            TreeNode p = root;
    
            while(p != null || !stack.isEmpty()) {
                if(p != null) {
                    stack.push(p);
                    p = p.left;
                } else {
                    p = stack.pop();
                    result.add(p.val);
                    p = p.right;
                }
            }
    
            return result;
        }
    
        public static void postOrderTravel(TreeNode root) {
    
            List<Integer> result = new ArrayList<>();
            if(root == null) {
                return result;
            }
    
            if(root != null) {
                Stack<TreeNode> stack1 = new Stack<>();
                Stack<TreeNode> stack2 = new Stack<>();
    
                stack1.push(root);
                while(!stack1.isEmpty()) {
                    TreeNode cur = stack1.pop();
                    stack2.push(cur);
    
                    if(cur.left != null) {
                        stack1.push(cur.left);
                    }
    
                    if(cur.right != null) {
                        stack1.push(cur.right);
                    }
                }
    
                while(!stack2.isEmpty()) {
                    //System.out.println(stack2.pop().val);
                    result.add(stack2.pop().val);
                }
            }
        }
    }
    

      

  • 相关阅读:
    Android中Handler的使用
    Android ListView使用
    Android ListView的XML属性
    Android ListView几个重要属性
    Android设置日期DatePickerDialog
    Android资源文件说明
    Android使用xml文件中的array资源
    Android:控件Spinner实现下拉列表
    如何搭建个人博客网站(Mac)
    SVProgressHUD源码解读(2.0.3)
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10658321.html
Copyright © 2011-2022 走看看