1. 程式人生 > 實用技巧 >物件和物件引用

物件和物件引用

目錄

二叉樹遍歷

前序:根左右

中序:左根右

後序:左右根

深度優先

前序遍歷

144. 二叉樹的前序遍歷

給定一個二叉樹,返回它的 前序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [1,2,3]
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        self.preorder(root,res)
        return res

    def preorder(self,root,res):
        if root:
            res.append(root.val)
            if root.left:
                self.preorder(root.left,res)
            if root.right:
                self.preorder(root.right,res)
#棧
#根左右,先將根節點入棧,在依次入右節點、左節點
class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        stack = []
        stack.append(root)  #根節點入棧
        while stack:
            root = stack.pop()
            if root:
                res.append(root.val)
                stack.append(root.right)
                stack.append(root.left)
        return res

中序遍歷

94. 二叉樹的中序遍歷

給定一個二叉樹,返回它的中序 遍歷。

示例:

輸入: [1,null,2,3]
   1
    \
     2
    /
   3

輸出: [1,3,2]
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

#遞迴
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        self.helper(root,res)
        return res
    def helper(self,root,res):
        if root:
            if root.left:
                self.helper(root.left,res)
            res.append(root.val)
            if root.right:
                self.helper(root.right,res)
#使用棧
class Solution:
    def inorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        stack = []
        cur = root
        while cur or stack:
            while cur:
                stack.append(cur)
                cur = cur.left
            cur = stack.pop()
            res.append(cur.val)
            cur = cur.right
        return res

後序遍歷

145. 二叉樹的後序遍歷

給定一個二叉樹,返回它的 後序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
    \
     2
    /
   3 

輸出: [3,2,1]
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def postorder(root):
            if root:
                if root.left:
                    postorder(root.left)
                if root.right:
                    postorder(root.right)
                res.append(root.val)
        postorder(root)
        return res
#棧
#根左右  轉換為  根右左  逆序為  左右根
class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        res = []
        stack = []
        stack.append(root)
        while stack:
            root = stack.pop()
            res.append(root.val)
            if root.left:
                stack.append(root.left)
            if root.right:
                stack.append(root.right)
        return res[::-1]

廣度優先

層次遍歷

102. 二叉樹的層序遍歷

給你一個二叉樹,請你返回其按 層序遍歷 得到的節點值。 (即逐層地,從左到右訪問所有節點)。

示例:
二叉樹:[3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回其層次遍歷結果:

[
  [3],
  [9,20],
  [15,7]
]
#按照每層遍歷
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        res,queue = [],[]
        queue.append([root])
        res.append([root.val])
        while queue:
            root = queue.pop(0)
            level,level_node = [],[]
            for node in root:
                if node.left:
                    level_node.append(node.left)
                    level.append(node.left.val)
                if node.right:
                    level_node.append(node.right)
                    level.append(node.right.val)
            if level_node:
                queue.append(level_node)
            if level:
                res.append(level)
        return res
class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        if not root:
            return []
        res,queue = [],[]
        queue.append([root])
        level = 0
        while queue:
            root = queue.pop(0)
            res.append([])
            level_node = []
            for node in root:
                res[level].append(node.val)
                if node.left:
                    level_node.append(node.left)
                if node.right:
                    level_node.append(node.right)
            if level_node:
                queue.append(level_node)
            level += 1
        return res

前面的方法過於混亂,直接使用BFS即可
python

class Solution:
    def levelOrder(self, root: TreeNode) -> List[List[int]]:
        queue, res = [], []
        if not root:
            return res
        queue.append(root)
        while queue:
            temp = []
            length = len(queue)
            while length>0:
                node = queue.pop(0)
                temp.append(node.val)
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
                length -= 1;
            res.append(temp)
        return res

java

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        List<List<Integer>> res = new ArrayList<List<Integer>>();

        if(root != null) queue.offer(root);
        while(!queue.isEmpty()){
            List<Integer> temp = new ArrayList<Integer>();
            int len = queue.size();
            for(int i=0; i<len; i++){
                TreeNode node = queue.poll();
                temp.add(node.val);
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
            res.add(temp);
        }
        return res;
    }
}