【每日一题】【栈】【递归】【遍历】2021年12月1日-94. 二叉树的中序遍历

TreeNode给定一个二叉树的根节点 root ,返回它的 中序 遍历。

 

 

 

 两种方式:递归(先序后序也要掌握)或非递归

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 //简单的递归方式
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        inOrder(root, list);
        return list;
    }

    public void inOrder(TreeNode root, List<Integer> list) {
        if(root == null) {
            return;
        }
        inOrder(root.left, list);
        list.add(root.val);
        inOrder(root.right, list);
    }
}
//非递归方式
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
     //Deque<TreeNode> stack = new LinkedList<TreeNode>();
//栈非空是isEmpty()而不是!=null while(root != null || !stack.isEmpty()) { while(root != null) { stack.push(root); root = root.left; } root = stack.pop(); list.add(root.val); root = root.right; } return list; } }

 

posted @ 2021-12-01 20:09  哥们要飞  阅读(36)  评论(0编辑  收藏  举报