代码随想录算法训练营第14天| 144.二叉树的前序遍历、145.二叉树的后序遍历、94.二叉树的中序遍历

144. 二叉树的前序遍历

难度简单940

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

class Solution {
    public List preorderTraversal(TreeNode root) {
        List res = new LinkedList<>();
        Deque s = new LinkedList<>();
        TreeNode cur = root ;
        while(cur != null || !s.isEmpty()){
            if(cur != null){
                res.add(cur.val);
                s.push(cur);
                cur = cur.left;
            }else{
                 cur = s.pop();
                 cur = cur.right;
            }
        }
        return res;
    }
}

 

94. 二叉树的中序遍历

难度简单1615

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

 

class Solution {
    public List inorderTraversal(TreeNode root) {
    List res = new LinkedList<>();
        Deque s = new LinkedList<>();
        TreeNode cur = root ;
        while(cur != null || !s.isEmpty()){
            if(cur != null){
                s.push(cur);
                cur = cur.left;
            }else{
                 cur = s.pop();
                 res.add(cur.val);
                 cur = cur.right;
            }
        }
        return res;
    }
}

 145. 二叉树的后序遍历

 给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 

class Solution {
    List res;
    public List postorderTraversal(TreeNode root) {
        res = new LinkedList<>();
        //得到中右左 然后反转成左右中
        Deque s = new LinkedList<>();
        TreeNode cur = root;
        while(!s.isEmpty() || cur != null ){
            if(cur != null){
                s.push(cur);
                //System.out.println(cur.val);
                res.add(cur.val);
                cur = cur.right;
            }else{
                cur = s.pop().left;
            }
        }
        Collections.reverse(res);
        return res;
    }
}

 

 

你可能感兴趣的:(代码训练营刷题,数据结构)