• 二叉树的遍历(循环方式)


    前序遍历(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;
        }
  • 相关阅读:
    网络层协议
    交换机原理
    复习
    网络布线和数据转换
    计算机网络参考模型
    Linux常用命令2
    Linux常用命令1
    服务器分类、硬盘分类
    TCP三次握手和断开四次挥手
    向HDFS中指定的文件追加内容,由用户指定内容追加到原有文件的开头或结尾。
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/8733110.html
Copyright © 2020-2023  润新知