zoukankan      html  css  js  c++  java
  • 二叉树的遍历(循环方式)

    前序遍历(Preorder Traverse)

    根结点-左子树-右子树

    Java代码实现:

    public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> ret = new ArrayList<Integer>();
            if(root == null)
                return ret;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()){
                if(cur != null){
                    ret.add(cur.val);
                    stack.push(cur);
                    cur = cur.left;
                }else{
                    TreeNode node = stack.pop();
                    cur = node.right;
                }
            }
            return ret;
        }

    后序遍历(postorder traverse)

    左子树-右子树-根结点

    代码实现:

    public List<Integer> postorderTraversal(TreeNode root) {
            LinkedList<Integer> ret = new LinkedList<Integer>();
            if(root == null)
                return ret;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(cur != null || !stack.isEmpty()){
                if(cur != null){
                    stack.push(cur);
                    ret.addFirst(cur.val);
                    cur = cur.right;
                }else{
                    TreeNode node = stack.pop();
                    cur = node.left;
                }
            }
            return ret;
        }

    中序遍历(inorder traverse):

    左子树-根结点-右子树

    代码实现:

     public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> ret = new ArrayList<Integer>();
            if(root == null)
                return ret;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode cur = root;
            while(!stack.isEmpty() || cur != null){
                if(cur != null){
                    stack.push(cur);
                    cur = cur.left;
                }else{
                    TreeNode node = stack.pop();
                    ret.add(node.val);
                    cur = node.right;
                }
            }
            return ret;
        }
  • 相关阅读:
    函数间的调用关系
    二分法原理
    图片1
    C函数讲解
    图片2
    图片1
    图片2
    函数间的调用关系
    C函数讲解
    二分法原理
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/8733110.html
Copyright © 2011-2022 走看看