美文网首页LeeCode题目笔记
二叉树的中序遍历

二叉树的中序遍历

作者: Antrn | 来源:发表于2019-08-11 21:01 被阅读0次

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

    示例:

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

    2
    /
    3

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

    C++1
    class Solution {
        List<Integer> res = new LinkedList<Integer>();
        public List<Integer> inorderTraversal(TreeNode root) {
            if(root == null)
                return res;
            inorderTraversal(root.left);
            res.add(root.val);
            inorderTraversal(root.right);
            return res;
        }
    }
    
    C++2
    class Solution {
        List<Integer> res = new LinkedList<Integer>();
        public List<Integer> inorderTraversal(TreeNode root) {
            res.clear();
            if(root == null)
                return res;
            Stack<TreeNode> stack = new Stack<TreeNode>();
            while(!stack.isEmpty() || root != null) {
                if(root != null) {
                    stack.push(root);
                    root = root.left;
                } else {
                    root = stack.pop();
                    res.add(root.val);
                    root = root.right;
                }
            }
            return res;
        }
    }
    

    相关文章

      网友评论

        本文标题:二叉树的中序遍历

        本文链接:https://www.haomeiwen.com/subject/tutejctx.html