zoukankan      html  css  js  c++  java
  • Leetcode:二叉树的中序遍历

    Leetcode: 二叉树的中序遍历


    中序遍历的流程:一直往左找,找到最左边的元素访问了之后,因为不存在左孩纸,所以访问完之后,再访问右子树,当右子树访问完,说明该左节点访问结束,就该回溯到上一个左节点,以此类推。

    题目:
    给定一个二叉树,返回它的中序遍历。

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

    Python 实现

    # Definition for a binary tree node.
    # class TreeNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution(object):
        def inorderTraversal(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            """
            思路:先往左访问到底,然后访问最左的第一个元素(不存在左孩子了),再去访问他的右子树,右子树访问完,回溯到上一个左孩子,进行访问,
            """
            result = []
            stack = []
            while True:
                while root:
                    stack.append(root)
                    root = root.left # 一直往左走
                if len(stack) == 0:
                    return result
                root = stack.pop()
                result.append(root.val) # 访问最左边的
                root = root.right # 访问最右边的
                
    

    C语言实现

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     struct TreeNode *left;
     *     struct TreeNode *right;
     * };
     */
    /**
     * Return an array of size *returnSize.
     * Note: The returned array must be malloced, assume caller calls free().
     */
    int* inorderTraversal(struct TreeNode* root, int* returnSize) {
        int *result = (int *)malloc(sizeof(int)*100);
        struct TreeNode *stack[100];
        int top = -1;
        int i = 0;
        while(true){
           while(root){
               stack[++top] = root;
               root = root->left; //往左走到底,就可以访问
           } 
           if(top == -1){
               *returnSize = i;
               return result;
           }
           root = stack[top--]; //拿到最左边的点,访问
           result[i++] = root->val;
           root = root->right; //访问完,就该访问右边的了。
        }
        
    }
    
  • 相关阅读:
    python学习之路-10 网络编程之进阶
    python学习之路-9 socket网络编程
    使用cx_Freeze 将python3代码打包成.exe程序
    如何在已经存在python2的linux环境上安装python3
    python学习之路-8 面向对象之进阶
    python学习之路-7 模块configparser/xml/shutil/subprocess以及面向对象初级入门
    java mybatis XML文件中大于号小于号转义
    java dom4j写入XML
    notepad++ 行末尾添加指定字符
    JQ 动态加载多选框--随记
  • 原文地址:https://www.cnblogs.com/xmxj0707/p/9669348.html
Copyright © 2011-2022 走看看