C/C++教程

leetcode-0094 二叉树的中序遍历

本文主要是介绍leetcode-0094 二叉树的中序遍历,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/**
 * 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<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while( root != null || !stack.isEmpty()){
            while( root != null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }

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



    public void accessTree(TreeNode root, List<Integer> res){
        if(root == null){
            return;
        }
        accessTree(root.left, res);
        res.add(root.val);
        accessTree(root.right, res);
    }
}
这篇关于leetcode-0094 二叉树的中序遍历的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!