Skip to content

Latest commit

 

History

History
77 lines (70 loc) · 2.13 KB

94.二叉树的中序遍历.md

File metadata and controls

77 lines (70 loc) · 2.13 KB

方法一:递归。

中序遍历的顺序:左 - 中 - 右,就按照这个顺序递归,只有到中的时候将节点元素添加到List中

/**
 * 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> list = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) return list;
        // 左
        inorderTraversal(root.left);
        // 中
        list.add(root.val);
        // 右
        inorderTraversal(root.right);
        return list;
    }
}

第二种:迭代。因为中序遍历的顺序是左 - 中 - 右,而每个节点又都遵守这样的访问顺序,所以对于任意一个节点而言都是一直向左访问到最左下角的叶子节点,然后将栈顶元素(最左下角叶子节点的父结点)弹出,即为中。然后将root指向root的右子树按照相同的规则访问。

/**
 * 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> list = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        if (root == null) return list;
        while (root != null || !stack.isEmpty()) {
            // 一直向左
            while (root != null) {
                stack.addLast(root);
                root = root.left;
            }
            // 中
            root = stack.pollLast();
            list.add(root.val);
            // y
            root = root.right;
        }
        return list;
    }
}