zoukankan      html  css  js  c++  java
  • leetcode| 94. 二叉树的中序遍历

    ##给定一个二叉树,返回它的中序遍历。 示例:

    输入: [1,null,2,3]
    1

    2
    /
    3

    输出: [1,3,2]
    进阶: 递归算法很简单,你可以通过迭代算法完成吗? 栈。

    思路

    时间复杂度O(n),空间复杂度O(lgn)。

    递归代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        private void recur(TreeNode root, List<Integer> ans) {
            if(root != null) {
                if(root.left != null) {
                    recur(root.left, ans);
                }
                ans.add(root.val);
                if(root.right != null) {
                    recur(root.right, ans);
                }
            }
        }
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> ans = new ArrayList<Integer>();
            recur(root, ans);
            return ans;
        }
    }
    

    非递归代码

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public List<Integer> inorderTraversal(TreeNode root) {
            List<Integer> ans = new ArrayList<Integer>();
            Stack<TreeNode> stack = new Stack<TreeNode>();
            TreeNode curr = root;
            while(curr != null || !stack.isEmpty()) {
                while(curr != null) {
                    stack.push(curr);
                    curr = curr.left;
                }
                curr = stack.pop();
                ans.add(curr.val);
                curr = curr.right;
            }
            return ans;
        }
    }
    

    链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

  • 相关阅读:
    程序的机器级表示(一)
    virtual memory(1)
    Python定义参数数量可变的method的问题
    存储器结构层次(四)
    CAShapeLayer
    cell
    远程服务器推送
    keyboad
    search搜索
    Cocoopod
  • 原文地址:https://www.cnblogs.com/ustca/p/12319073.html
Copyright © 2011-2022 走看看