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

  • 相关阅读:
    五月一日工作感悟
    Loadrunner 性能指标
    tcp ,http .udp
    Loadrunner 面试常见问题
    抓包不求人
    性能测试自动化测试平台
    jmeter 控制器
    转:java中String使用equals和==比较的区别
    转:Java对象及对象引用变量
    排序算法小结
  • 原文地址:https://www.cnblogs.com/ustca/p/12319073.html
Copyright © 2011-2022 走看看