首页 > 其他 > 详细

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

时间:2019-05-11 23:21:37      阅读:189      评论:0      收藏:0      [点我收藏+]

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

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

LeetCode94. Binary Tree Inorder Traversal

示例:
输入: [1,null,2,3]

   1
         2
    /
   3

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

Java 实现
Iterative Solution

import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

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

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

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new LinkedList<>();
        if (root == null) {
            return result;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            result.add(cur.val);
            cur = cur.right;
        }
        return result;
    }
}

Recursive Solution

import java.util.LinkedList;
import java.util.List;

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

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

class Solution {
    List<Integer> result = new LinkedList<>();

    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null) {
            return result;
        }
        inorderTraversal(root.left);
        result.add(root.val);
        inorderTraversal(root.right);
        return result;
    }
}

相似题目

参考资料

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

原文:https://www.cnblogs.com/hglibin/p/10850446.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!