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

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?


方法1:(递归遍历)

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

时间复杂度:O(n)

空间复杂度:O(n)


方法2:(利用栈进行遍历)

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

时间复杂度:O(n) 

空间复杂度:O(n)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/85046785