94、二叉树的中序遍历

  1. 94、二叉树的中序遍历
    1. 示例:
  • 题解
    1. 1、递归实现
    2. 2、利用栈实现
  • 94、二叉树的中序遍历

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

    示例:

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

    进阶: 递归算法很简单,你可以通过迭代算法完成吗?

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

    题解

    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> res = new ArrayList<>();
            inorderTraversal(root,res);
            return res;
        }
    
        private void  inorderTraversal(TreeNode root,List<Integer> res) {
            if (root != null) {
                inorderTraversal(root.left,res);
                res.add(root.val);
                inorderTraversal(root.right,res);
            }
        }
    }
    

    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> res = new ArrayList<>();
            Stack<TreeNode> list = new Stack<>();
            TreeNode curTree = root;
            while(curTree != null || !list.isEmpty()) {
                // 遍历到最左子树
                if (curTree.left != null) {
                    list.push(curTree);// 存入栈中
                    curTree = curTree.left;
                } else {
                    // 打印数据
                    res.add(curTree.val);
                    // 迭代curTree下的最右子树
                    curTree = curTree.right;
                    // 没有右子树,打印节点
                    while(curTree == null && !list.isEmpty()) {
                        curTree = list.peek();
                        res.add(curTree.val);
                        list.pop();
                        curTree = curTree.right;
                    }
                }
            }
            return res;
        }
    }
    

    转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

    💰

    Title:94、二叉树的中序遍历

    Count:310

    Author:攀登

    Created At:2020-07-26, 00:19:44

    Updated At:2024-06-15, 15:52:32

    Url:http://jiafeimao-gjf.github.io/2020/07/26/94%E3%80%81%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E4%B8%AD%E5%BA%8F%E9%81%8D%E5%8E%86/

    Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

    ×

    Help us with donation