🌕 94. 二叉树的䞭序遍历

吞䜛童子2022幎6月9日
  • algorithm
  • tree
小于 1 分钟

🌕 94. 二叉树的䞭序遍历

隟床: 🌕

问题描述

img_4.png


解法 1 - 迭代

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        // 思路
        // 迭代 - 借助 蟅助栈
        // 每次从栈顶取出元玠若有巊节点则巊节点持续压栈
        // 压䞀次右节点
        List<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();
        TreeNode cur = root;
        while(cur != null || !stack.isEmpty()) {
            if(cur != null) {
                while(cur != null) {
                    stack.push(cur);
                    cur = cur.left;
                }
            }
            cur = stack.pop();
            res.add(cur.val);
            cur = cur.right;
        }
        return res;
    }
}

蟓出 1

img_5.png


解法 2 - 递園

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        // 思路
        // 递園
        mySol(root);
        return res;
    }

    private void mySol(TreeNode root) {
        // 递園终止条件
        if(root == null) {
            return;
        }
        // root != null
        mySol(root.left);
        res.add(root.val);
        mySol(root.right);
    }
}

蟓出 2

img_3.png

䞊次猖蟑于: 2022/10/10 䞋午8:43:48
莡献者: liuxianzhishou