首页 > 其他 > 详细

leetcode| 94. 二叉树的中序遍历

时间:2020-02-16 23:24:32      阅读:55      评论:0      收藏:0      [点我收藏+]

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

示例:

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

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

思路

时间复杂度O(n),空间复杂度O(lgn)。

递归代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private void recur(TreeNode root, List<Integer> ans) {
        if(root != null) {
            if(root.left != null) {
                recur(root.left, ans);
            }
            ans.add(root.val);
            if(root.right != null) {
                recur(root.right, ans);
            }
        }
    }
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<Integer>();
        recur(root, ans);
        return ans;
    }
}

非递归代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<Integer>();
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode curr = root;
        while(curr != null || !stack.isEmpty()) {
            while(curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            curr = stack.pop();
            ans.add(curr.val);
            curr = curr.right;
        }
        return ans;
    }
}

链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

leetcode| 94. 二叉树的中序遍历

原文:https://www.cnblogs.com/ustca/p/12319073.html

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