码迷,mamicode.com
首页 > 其他好文 > 详细

94. Binary Tree Inorder Traversal - Medium

时间:2019-01-01 11:02:35      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:order   value   do it   des   empty   ISE   new   span   rsa   

Given a binary tree, return the inorder traversal of its nodes‘ values.

Example:

Input: [1,null,2,3]
   1
         2
    /
   3

Output: [1,3,2]

Follow up: Recursive solution is trivial, could you do it iteratively?

 

M1: recursive

time: O(n), space: O(height)

/**
 * 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> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        
        inorder(root, res);
        return res;
    }
    
    public void inorder(TreeNode node, List<Integer> res) {
        if(node == null) {
            return;
        }
        
        inorder(node.left, res);
        res.add(node.val);
        inorder(node.right, res);
    }
}

 

M2: iterative

time: O(n), space: O(n)  -- worst case

/**
 * 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> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        
        Stack<TreeNode> s = new Stack<>();
        TreeNode cur = root;
        
        while(cur != null || !s.isEmpty()) {
            while(cur != null) {
                s.push(cur);
                cur = cur.left;
            }
            
            cur = s.pop();
            res.add(cur.val);
            cur = cur.right;
        }
        
        return res;
    }
}

 

94. Binary Tree Inorder Traversal - Medium

标签:order   value   do it   des   empty   ISE   new   span   rsa   

原文地址:https://www.cnblogs.com/fatttcat/p/10204202.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!