94. 二叉树的中序遍历 Leetcode java

题目:

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

示例:

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

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

递归法:

import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode(int x) { val = x; }
 * }
 */
public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {

    public List inorderTraversal(TreeNode root) {
        List res = new ArrayList<>();
        helper(root, res);
        return res;
    }

    public void helper(TreeNode root, List res) {
        if (root != null) {
            if (root.left != null) {
                helper(root.left, res);
            }

        res.add(root.val);

            if (root.right != null) {
                helper(root.right, res);
            }
        }
    }

}

迭代法:

利用栈

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

class Solution {

    public List inorderTraversal(TreeNode root) {

        List res=new ArrayList<>();
        Stack stack=new Stack<>();
        TreeNode curr=root;
        while (curr!=null||!stack.isEmpty()){
            while (curr!=null){
                stack.push(curr);
                curr=curr.left;
            }
            curr=stack.pop();
            res.add(curr.val);
            curr=curr.right;
        }
        return res;
    }

}

 

你可能感兴趣的:(Leetcode,树,leetcode,二叉树)