Leetcode刷题之路(141-150)

144.二叉树的前序遍历

二叉树的前序遍历题目链接

  • 方法一:递归法
List<Integer> results = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
         if(root!=null){
             results.add(root.val);
             preorderTraversal(root.left);
             preorderTraversal(root.right);
         }
         return results;
    }
  • 方法二:迭代法,通过栈来实现
List<Integer> results = new ArrayList<>();
    public List<Integer> preorderTraversal(TreeNode root) {
        TreeNode p = root;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(p);
        while(!stack.isEmpty()){
            TreeNode treeNode = stack.pop();
            if(treeNode!=null){
                results.add(treeNode.val);
                stack.push(treeNode.right);
                stack.push(treeNode.left);
            }
        }
        return results;
    }
public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        while(!stack.isEmpty()||p!=null){
            while(p!=null){
                stack.push(p);
                results.add(p.val);
                p=p.left;
            }
            p=stack.pop();
            p=p.right;
        }
        return results;
    }

145.二叉树的后序遍历

二叉树的后序遍历题目链接

  • 方法一:递归法
List<Integer> results = new ArrayList<>();
    public List<Integer> postorderTraversal(TreeNode root) {
            if(root!=null){
                postorderTraversal(root.left);
                postorderTraversal(root.right);
                results.add(root.val);
            }
            return results;
    }
  • 方法二:迭代法,还是用栈来实现,不过要倒起插入还搞点…
public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> results = new ArrayList<>();
        if(root==null){
            return results;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode treeNode = stack.pop();
            if(treeNode.left!=null){
                stack.push(treeNode.left);
            }
            if(treeNode.right!=null){
                stack.push(treeNode.right);
            }
            results.add(0,treeNode.val);

        }
        return results;
    }

你可能感兴趣的:(leetcode刷题之路,leetcode)