算法: 二叉树中序遍历94. Binary Tree Inorder Traversal

Posted 架构师易筋

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了算法: 二叉树中序遍历94. Binary Tree Inorder Traversal相关的知识,希望对你有一定的参考价值。

94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes’ values.

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Example 4:

Input: root = [1,2]
Output: [2,1]

Example 5:

Input: root = [1,null,2]
Output: [1,2]

Constraints:

The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

递归解法

同一套代码,仅仅list.add(root.val); 位置的不同就可以实现 前中后序。

/**
 * 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<>();
        recursive(root, list);
        
        return list;
    }
    
    private void recursive(TreeNode root, List<Integer> list) {
        if (root == null) return;
        // preOrder
        recursive(root.left, list);
        // inOrder
        list.add(root.val);
        recursive(root.right, list);
        // afterOrder
    }
}

遍历解法

/**
 * 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<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            TreeNode current = stack.pop();
            list.add(current.val);
            root = current.right;
        }
        
        return list;
    }
}

以上是关于算法: 二叉树中序遍历94. Binary Tree Inorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode94二叉树中序遍历

leetCode 94.Binary Tree Inorder Traversal(二叉树中序遍历) 解题思路和方法

二叉树中序遍历

算法:中序遍历二叉树94. Binary Tree Inorder Traversal

leetcode 94.Binary Tree Inorder Traversal 二叉树的中序遍历

LeetCode 94 Binary Tree Inorder Traversal(二叉树的中序遍历)+(二叉树迭代)