zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge20 之 二叉树中序遍历

    因为题目为二叉搜索树找到第k大的数,所以对二叉搜索树中序遍历一定是有序的。

    分为两种:递归 和 迭代(栈)

    JAVA

    /**
     * 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 LinkedList<Integer> inorder(TreeNode root, LinkedList<Integer> arr){
            if(root == null) return arr;
            inorder(root.left, arr);
            arr.add(root.val);
            inorder(root.right, arr);
            return arr;
        }
        public int kthSmallest(TreeNode root, int k) {
            LinkedList<Integer> nums = inorder(root, new LinkedList<>());
            return nums.get(k-1);
        }
    }
    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Deque<TreeNode> stack = new LinkedList<>();
            List<Integer> nums = new LinkedList<>();
            TreeNode cur = root;
            while(!stack.isEmpty() || cur != null){
                while(cur != null){
                    stack.addLast(cur);
                    cur = cur.left;
                }
                cur = stack.removeLast();
                nums.add(cur.val);
                cur = cur.right;
            }
            return nums.get(k-1);
        }
    }

    Python3

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def kthSmallest(self, root: TreeNode, k: int) -> int:
            num = []
            return self.inorder(root, num)[k-1]
        def inorder(self, root, res):
            if root == None:
                return res
            self.inorder(root.left, res)
            res.append(root.val)
            self.inorder(root.right, res)
            return res
    class Solution:
        def kthSmallest(self, root: TreeNode, k: int) -> int:
            stack = []
            res = []
            cur = root
            while stack or cur:
                if cur:
                    stack.append(cur)
                    cur = cur.left
                else: 
                    cur = stack.pop()
                    res.append(cur.val)
                    cur = cur.right
            return res[k-1]
  • 相关阅读:
    【Jenkins】jenkins 配置腾讯企业邮箱
    Monkey 用户指南(译)
    Windows,easygui 安装
    python笔记:list--pop与remove的区别
    递归--Java_汉诺塔
    appium安装 For windows
    【web开发--js学习】functionName 如果是一个属性值,函数将不会被调用
    python爬取煎蛋网图片
    pv&pvc
    docker
  • 原文地址:https://www.cnblogs.com/yawenw/p/12944367.html
Copyright © 2011-2022 走看看