zoukankan      html  css  js  c++  java
  • 二叉树的遍历

    //144. Binary Tree Preorder Traversal (Medium)
        public List<Integer> preorderTraversal(TreeNode root){
            List<Integer> ret = new ArrayList<Integer>();
            if(root==null){
                return ret;
            }
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            while(!stack.isEmpty()){
                TreeNode node = stack.pop();
                ret.add(node.value);
                if(node.right!=null){
                    stack.add(node.right);
                }
                if(node.left!=null){
                    stack.add(node.right);
                }
            }
            return ret;
        }
        
        //145. Binary Tree Postorder Traversal (Medium)
        //前序遍历为 root -> left -> right,后序遍历为 left -> right -> root。可以修改前序遍历成为 root -> right -> left,那么这个顺序就和后序遍历正好相反。
        public List<Integer> postorderTraversal(TreeNode root){
            List<Integer> ret = new ArrayList<Integer>();
            if(root==null){
                return ret;
            }
            Stack<TreeNode> stack = new Stack<TreeNode>();
            stack.push(root);
            while(!stack.isEmpty()){
                TreeNode node = stack.pop();
                ret.add(node.value);
                if(root.left!=null){
                    stack.push(node.left);
                }
                if(root.right!=null){
                    stack.push(node.right);
                }
            }
            Collections.reverse(ret);
            return ret;
        }
        //94. Binary Tree Inorder Traversal (Medium)
        public List<Integer> inorderTraversal(TreeNode root){
            List<Integer> ret = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode curr = root;
            while(curr!=null || !stack.isEmpty()){
                while(curr!=null){
                    stack.push(curr);
                    curr = curr.left;
                }
                curr = stack.pop();
                ret.add(curr.value);
                curr = curr.right;
            }
            return ret;
        }
  • 相关阅读:
    JUC原子类 1
    线程优先级和守护线程
    多线程中断
    关于html5不支持frameset的解决方法
    shell中$0,$?,$!等的特殊用法
    Linux GCC常用命令
    C/C++中extern关键字详解
    js实现iframe自适应高度
    java线程安全总结
    Linux平台Java调用so库-JNI使用例子
  • 原文地址:https://www.cnblogs.com/helloworldmybokeyuan/p/13446425.html
Copyright © 2011-2022 走看看