二叉树中序遍历

二叉树中序遍历

方法一

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
         Stack<TreeNode> stack = new Stack<>();
         List<Integer> res = new ArrayList<>();
         TreeNode cur = root;
         while(cur!=null || !stack.isEmpty()){
             if(cur != null){
                 stack.push(cur);
                 cur = cur.left;
            }else{
                cur = stack.pop();
                res.add(cur.val);
                cur = cur.right;
            }
         }
         return res;
    }
}

方法二

递归

class Solution {
    List<Integer> res = new ArrayList<>();
    public List<Integer> inorderTraversal(TreeNode root) {
        dfs(root);
        return res;
    }
    private void dfs(TreeNode node){
        if(node == null)return; 
        dfs(node.left);
        res.add(node.val);
        dfs(node.right);
    }
}
posted @ 2020-07-30 02:02  CyberPelican  阅读(102)  评论(0编辑  收藏  举报