数据结构与算法-二叉树-中序遍历

二叉树的中序遍历

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

示例 1:

数据结构与算法-二叉树-中序遍历_第1张图片

输入:root = [1,null,2,3]
输出:[1,3,2]

递归版本实现

/**
 * 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> res =  new ArrayList<>();
          inorder( root,res);
          return res;
    }

    public void inorder(TreeNode root,List<Integer> res){
        if(root == null) return;
        if(root.left != null) {
            inorder(root.left,res);
        }
        res.add(root.val);
        if(root.right != null) {
            inorder(root.right,res);
        }
    }
}

迭代版本实现

思路:

  1. 先把当前节点和所有左节点放入栈中
  2. 出栈,将出栈节点放入res中
  3. 将currentNode指向出栈节点的右节点

数据结构与算法-二叉树-中序遍历_第2张图片
数据结构与算法-二叉树-中序遍历_第3张图片

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

  
}

你可能感兴趣的:(数据结构与算法,数据结构,leetcode)