每日算法 - 二叉树中序遍历(基础算法)

目录

题目

解题思路

中序遍历代码

递归(最基础)

莫瑞斯

总结

完整测试代码



题目

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

示例:

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


解题思路

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/er-cha-shu-de-zhong-xu-bian-li-by-leetcode/

 

 


中序遍历代码

  • 递归(最基础)

public List < Integer > inorderTraversal(TreeNode root) {
        List < Integer > res = new ArrayList < > ();
        helper(root, res);
        return res;
    }

    public void helper(TreeNode root, List < Integer > res) {
        if (root != null) {
            // 左
            if (root.left != null) {
                helper(root.left, res);
            }
            // 根
            res.add(root.val);
            // 右
            if (root.right != null) {
                helper(root.right, res);
            }
        }
    }

 


public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = 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(); 
            res.add(curr.val); // 先存左,然后根,最后右
            curr = curr.right;
        }
        return res;
    }


  • 莫瑞斯

  public List < Integer > inorderTraversal(TreeNode root) {
        List < Integer > res = new ArrayList < > ();
        TreeNode curr = root;
        TreeNode pre;
        while (curr != null) {
            if (curr.left == null) {
                res.add(curr.val);
                curr = curr.right; // move to next right node
            } else { // has a left subtree
                pre = curr.left;
                while (pre.right != null) { // find rightmost
                    pre = pre.right;
                }
                pre.right = curr; // put cur after the pre node
                TreeNode temp = curr; // store cur node
                curr = curr.left; // move cur to the top of the new tree
                temp.left = null; // original cur left be null, avoid infinite loops
            }
        }
        return res;
    }

 


总结

1、中序遍历: 左 - 中 - 右;

2、三种方法掌握最基础的递归,能够使用栈,了解使用莫瑞斯;

 


完整测试代码

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;

/**
 * 前序遍历
 */
public class InorderTraversal {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.setLeft(new TreeNode(0));
        root.setRight(new TreeNode(2));
        root.getRight().setLeft(new TreeNode(3));
        root.getRight().setRight(new TreeNode(0));

        // 递归实现
        List<Integer> res = inorderTraversalByRecursive(root);

        // 迭代实现
        List<Integer> res2 = inorderTraversal(root);

        // Morris实现
        List<Integer> res3 = inorderTraversalByMorris(root);

        System.out.println("递归实现:");
        for (Integer item : res) {
            System.out.print(item + " ");
        }

        System.out.println(" ");
        System.out.println("迭代实现:");
        for (Integer item : res2) {
            System.out.print(item + " ");
        }

        System.out.println(" ");
        System.out.println("Morris实现:");
        for (Integer item : res2) {
            System.out.print(item + " ");
        }
    }

    /**
     * 迭代使用栈,中序遍历
     *
     * @param root
     * @return
     */
    public static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = 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();
            res.add(curr.val); // 先存左,然后根,最后右
            curr = curr.right;
        }
        return res;
    }

    /**
     * 递归
     */

    public static List<Integer> inorderTraversalByRecursive(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        helper(root, res);
        return res;
    }

    public static void helper(TreeNode root, List<Integer> res) {
        if (root != null) {
            // 左
            if (root.left != null) {
                helper(root.left, res);
            }
            // 根
            res.add(root.val);
            // 右
            if (root.right != null) {
                helper(root.right, res);
            }
        }
    }


    /**
     * Morris
     */

    public static List<Integer> inorderTraversalByMorris(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        TreeNode curr = root;
        TreeNode pre;
        while (curr != null) {
            if (curr.left == null) {
                res.add(curr.val);
                curr = curr.right; // move to next right node
            } else { // has a left subtree
                pre = curr.left;
                while (pre.right != null) { // find rightmost
                    pre = pre.right;
                }
                pre.right = curr; // put cur after the pre node
                TreeNode temp = curr; // store cur node
                curr = curr.left; // move cur to the top of the new tree
                temp.left = null; // original cur left be null, avoid infinite loops
            }
        }
        return res;
    }

}

 

输入如题,null用0代替。输出如下:

 

递归实现:
0 1 3 2 0  
迭代实现:
0 1 3 2 0  
Morris实现:
0 1 3 2 0 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常抱歉,作为一名 AI 语言模型,并没有能力直接进行编程和运行程。但是,我可以为您提供一些基础知识与思路,希望可以帮助您解决问题。 在二叉树、前和后是最基本且重要的三种遍方式,其指的是先访问左孩子结点,再访问右孩子结点,最后访问根结点。下面分别介绍二叉树和后的递归和非递归算法实现。 二叉树递归算法: ```c void inorderTraversal(TreeNode* root) { if (root != NULL) { inorderTraversal(root->left); // 访问左子树 printf("%d ", root->val); // 访问根节点 inorderTraversal(root->right); // 访问右子树 } } ``` 二叉树非递归算法:使用栈来实现 ```c void inorderTraversal(TreeNode* root) { stack<TreeNode*> st; TreeNode* p = root; while (p != NULL || !st.empty()) { if (p != NULL) { st.push(p); p = p->left; } else { p = st.top(); st.pop(); printf("%d ", p->val); p = p->right; } } } ``` 二叉树递归算法: ```c void postorderTraversal(TreeNode* root) { if (root != NULL) { postorderTraversal(root->left); postorderTraversal(root->right); printf("%d ", root->val); } } ``` 二叉树非递归算法:使用一个栈和两个指针来实现后 ```c void postorderTraversal(TreeNode* root) { stack<TreeNode*> st; TreeNode* p = root; TreeNode* last = NULL; // 上次访问的结点 while (p != NULL || !st.empty()) { if (p != NULL) { st.push(p); p = p->left; } else { TreeNode* top = st.top(); if (top->right != NULL && top->right != last) { // 如果右子树存在,且未被访问 p = top->right; } else { // 否则,访问该节点 st.pop(); printf("%d ", top->val); last = top; } } } } ``` 希望以上的内容可以对您编写程有所帮助,如果还有其他问题请随时提出。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值