Leetcode题目94.二叉树的中序遍历(中等)

题目描述:

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

示例:

输入: [1,null,2,3]
   1
    
     2
    /
   3

输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

思路解析:

1)递归:没啥说的,左子树->根->右子树顺序去遍历

2)迭代计算:用栈,再用一个指针模拟访问过程

代码实现:

1)递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
       //返回该二叉树的中序遍历
    public static List<Integer> inorderTraversal(TreeNode root) {

        List<Integer> res = new ArrayList<>();
        dfsTraversal(res, root);
        return res;
    }

    private static void dfsTraversal(List<Integer> res, TreeNode root) {
        if (root == null) {
            return;
        }
        dfsTraversal(res, root.left);
        res.add(root.val);
        dfsTraversal(res, root.right);
    }
}

2)迭代:

    public static List<Integer> inorderTraversal(TreeNode root) {

        //借助一个占来实现
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        if (root == null) {
            return res;
        }
        TreeNode pNode = root;
        while (!stack.isEmpty() || pNode != null) {
            while (pNode != null) {
                stack.push(pNode);
                pNode = pNode.left;
            }
            //出栈,弹出元素加入结果集
            TreeNode node = stack.pop();
            res.add(node.val);
            pNode = node.right;
        }
        return res;
    }

时间复杂度:O(n)。递归函数 T(n)=2⋅T(n/2)+1。
空间复杂度:最坏情况下需要空间O(n)(每个节点只有一颗子树),平均情况为O(logn)(满二叉树结构排列)。

原文地址:https://www.cnblogs.com/ysw-go/p/11820094.html