LeetCode_二叉树_简单_94.二叉树的中序遍历

x33g5p2x  于2022-03-22 转载在 其他  
字(0.8k)|赞(0)|评价(0)|浏览(231)

1.题目

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

示例 1:

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

示例 2:
输入:root = []
输出:[]

示例 3:
输入:root = [1]
输出:[1]

示例 4:

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

示例 5:

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

提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

2.思路

(1)回溯

3.代码实现(Java)

//思路1————回溯算法
public class Solution {
    
    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;
        }
    }
    
    //res用于保存最终结果
    LinkedList<Integer> res = new LinkedList<>();
    
    public List<Integer> inorderTraversal(TreeNode root) {
        backtrack(root);
        return res;
    }
    
    public void backtrack(TreeNode root) {
        if (root == null) {
            return;
        }
        //中序遍历:首先遍历左子树,然后访问根结点,最后遍历右子树。
        backtrack(root.left);
        res.add(root.val);
        backtrack(root.right);
    }
}

相关文章

微信公众号

最新文章

更多