精华内容
下载资源
问答
  • 二叉树的非递归遍历

    千次阅读 2019-12-16 13:04:14
    二叉树的非递归遍历

    https://yuanyu.blog.csdn.net/article/details/102639318 


    1 系统栈调用过程 

     

     

     

     


    2 把系统栈调用过程转化我自己的栈

     

     

     

     

     


    3 coding

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }
    /**
     * 144. 二叉树的前序遍历:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
     * 94. 二叉树的中序遍历:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
     * 145. 二叉树的后序遍历:https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
     */
    public class Solution {
        private static class Command {
            String s;   // go, print
            TreeNode node;
            Command(String s, TreeNode node) {
                this.s = s;
                this.node = node;
            }
        }
        //preorderTraversal
        //inorderTraversal
        //postorderTraversal
        public List<Integer> postorderTraversal(TreeNode root) {
            ArrayList<Integer> res = new ArrayList<>();
            if (root == null) {
                return res;
            }
            Deque<Command> stack = new ArrayDeque<>();
            stack.push(new Command("go", root));
            while (!stack.isEmpty()) {
                Command command = stack.pop();
                if (command.s.equals("print")) {
                    res.add(command.node.val);
                } else {//command.s.equals("go");
                    //后序遍历 stack.push(new Command("print", command.node));
                    if (command.node.right != null) {
                        stack.push(new Command("go", command.node.right));
                    }
                    //中序遍历 stack.push(new Command("print", command.node));
                    if (command.node.left != null) {
                        stack.push(new Command("go", command.node.left));
                    }
                    //前序遍历 stack.push(new Command("print", command.node));
                }
            }
            return res;
        }
    }

     

    展开全文
  • 本篇文章是对二叉树的非递归遍历进行了详细的分析介绍,需要的朋友参考下
  • 主要介绍了C语言二叉树的非递归遍历,包括了先序遍历、中序遍历与后序遍历,需要的朋友可以参考下

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 11,369
精华内容 4,547
关键字:

二叉树的非递归遍历