LeetCode #94 Binary Tree Inorder Traversal 中序遍歷二元樹

英文原文如下

Given the root of a binary tree, return the inorder traversal of its nodes’ values.

中文翻譯

給予一顆二元樹的根結點,回傳以中序遍歷得到的值

範例及題目限制

94_144_145-Constraints

解題思路

走訪整個二元樹通常有三種方式,分別是

  • Inorder 中序
  • Preorder 前序
  • Postorder 後序

而他們的差異就是在走訪節點的順序上面

以這次的中序遍歷來說,順序是 : 左子樹 ➡  父(根)節點 ➡  右子樹

C# 解決方案

方案1

public class Solution {
    
    public IList<int> InorderTraversal(TreeNode root) {
        List<int>res = new List<int>();
        if(root == null)
        {
            return res;
        } 
        return Inorder(res,root);
    }
    
    public IList<int> Inorder(IList<int> res,TreeNode root)
    {    
        if(root.left!=null)
        {
           res = Inorder(res,root.left); 
        }
        
        res.Add(root.val);
        
        if(root.right!=null)
        {
            res = Inorder(res,root.right); 
        }
        
        return res;
    }
}

採用遞迴的方式,要是左邊的樹還有東西,就會一直繼續走

Java解決方案

方案1

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer>res = new ArrayList<Integer>();
        if(root == null)
        {
            return res;
        } 
        return Inorder(res,root);
    }
    
    public List<Integer> Inorder(List<Integer> res,TreeNode root)
    {    
        if(root.left!=null)
        {
           res = Inorder(res,root.left); 
        }
        
        res.add(root.val);
        
        if(root.right!=null)
        {
            res = Inorder(res,root.right); 
        }
        
        return res;
    }
}

運行時間 : 0ms、0ms、0ms

Python3 解決方案

方案1

class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
    
        def Inorder(root):
            if(root.left != None):
                Inorder(root.left)

            res.append(root.val)

            if(root.right != None):
                Inorder(root.right)
        
        res = []
        if(root == None):
            return res
        
        Inorder(root)
        return res

JavaScript 解決方案

方案1

var inorderTraversal = function(root) {
    res = [];
    if(root == undefined)
    {
        return res;
    }
    return Inorder(res,root);
};

function Inorder(res,root)
{
    if(root.left!=undefined)
    {
       res = Inorder(res,root.left); 
    }

    res.push(root.val);

    if(root.right!=undefined)
    {
        res = Inorder(res,root.right); 
    }

    return res; 
}

結論

不得不說,我在二元樹這種資料結構上實在有夠弱的哈哈 (不過答案是我寫的沒錯!!)

找時間會再去重讀一下課本,再來跟大家分享

🧡如果這篇文章有幫上你的一點點忙,那是我的榮幸

🧡收藏文章或幫我點個廣告,那都是對我的支持

✅如有任何疑問,歡迎透過留言或messenger讓我知道 !

題目連結 : Binary Tree Inorder Traversal – LeetCode

一些隨機文章

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *