LeetCode
  • Introduction
  • 第一章: 基本结构
    • 1.1 数组
      • Q11. Container With Most Water
      • Q16. 3Sum Closest
      • Q118. Pascal's Triangle
      • Q119. Pascal's Triangle II
      • Q120. Triangle
      • Q134. Gas Station
    • 1.2 链表
      • Q2: Add Two Numbers
      • Q19. Remove Nth Node From End of List
      • Q82. Remove Duplicates from Sorted List II
      • Q86: Partition List
      • Q92. Reverse Linked List II
      • Q141. Linked List Cycle
      • Q142. Linked List Cycle II
      • Q147. Insertion Sort List
      • Q160. Intersection of Two Linked Lists
      • Q206. Reverse Linked List
    • 1.3 哈希
      • Q1: Two Sum
      • Q3. Longest Substring Without Repeating Characters
    • 1.4 堆栈
      • Q84: Largest Rectangle in Histogram
      • Q155. Min Stack
      • Q20. Valid Parentheses
      • Q225. Implement Stack using Queues
      • Q232. Implement Queue using Stacks
    • 1.5 树
      • Q94. Binary Tree Inorder Traversal
      • Q100. Same Tree
      • Q101. Symmetric Tree
      • Q102. Binary Tree Level Order Traversal
      • Q103. Binary Tree Zigzag Level Order Traversal
      • Q104. Maximum Depth of Binary Tree
      • Q105. Construct Binary Tree from Preorder and Inorder Traversal
      • Q106. Construct Binary Tree from Inorder and Postorder Traversal
      • Q107. Binary Tree Level Order Traversal II
      • Q108. Convert Sorted Array to Binary Search Tree
      • Q109. Convert Sorted List to Binary Search Tree
      • Q110. Balanced Binary Tree
      • Q111. Minimum Depth of Binary Tree
      • Q112. Path Sum
      • Q113. Path Sum II
      • Q114. Flatten Binary Tree to Linked List
      • Q116. Populating Next Right Pointers in Each Node
      • Q117. Populating Next Right Pointers in Each Node II
      • Q129. Sum Root to Leaf Numbers
      • Q144. Binary Tree Preorder Traversal
    • 1.6 图
    • 1.7 二进制
      • Q89. Gray Code
      • Q136. Single Number
      • Q137. Single Number II
      • Q191. Number of 1 Bits
      • Q190. Reverse Bits
    • 1.8 字符串
      • Q5. Longest Palindromic Substring
      • Q14. Longest Common Prefix
      • Q125. Valid Palindrome
  • 第二章: 动态规划
    • Q85: Maximal Rectangle
    • Q91. Decode Ways
    • Q121. Best Time to Buy and Sell Stock
    • Q198. House Robber
  • 第三章: 递归
    • Q17. Letter Combinations of a Phone Number
    • Q78. Subsets
    • Q86. Scramble String
    • Q90: Subsets II
  • 第四章:贪心
    • Q122. Best Time to Buy and Sell Stock II
  • 第五章:分治法
  • 第六章:数学
    • Q6. ZigZag Conversion
    • Q7. Reverse Integer
    • Q9. Palindrome Number
    • Q168. Excel Sheet Column Title
    • Q171. Excel Sheet Column Number
  • 第七章:查找
    • Q15. Three Sum
    • Q167. Two Sum II
    • Q169. Majority Element
  • 第八章:排序
Powered by GitBook
On this page
  • 144. Binary Tree Preorder Traversal
  • 分析
  • C++算法

Was this helpful?

  1. 第一章: 基本结构
  2. 1.5 树

Q144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal

Given a binary tree, return thepreordertraversal of its nodes' values.

For example: Given binary tree[1,null,2,3],

   1
    \
     2
    /
   3

return[1,2,3].

Note:Recursive solution is trivial, could you do it iteratively?

分析

用递归解决二叉树的遍历是非常普遍的解法,题目提出能否使用迭代来进行二叉树的先序遍历。

对于先序遍历,需要使用堆栈做辅助。首先树顶入栈,然后执行while循环直到堆栈为空。在循环中每次弹出栈顶元素,将结果保存在数组中然后再将弹出节点的右子树和左子树一次入栈。首先,例如树

      1
    /   \
   2     3
  / \   / \
 4   5 6   7
  1. 入栈,执行while循环.

  2. 弹出1,将3,2入栈。此时res=[1], stack=[3,2]

  3. 弹出2,将5,4入栈。此时res=[1, 2], stack=[3,5,4]

  4. 弹出4。res=[1,2,4], stack=[3,5]

  5. 弹出5。res=[1,2,4,5]. stack=[3]

  6. 弹出3,将7,6入栈。res=[1,2,4,5,3], stack=[7,6]

  7. 弹出6。res=[1,2,4,5,3,6], stack=[7]

  8. 弹出7。res=[1,2,4,5,3,6,7], stack=[]

  9. 栈为空,循环结束,返回res。

C++算法

递归

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        helper(root, res);
        return res;
    }
private:
    void helper(TreeNode* root, vector<int>& res){
        if (!root) return;
        res.push_back(root->val);
        if (root->left) helper(root->left, res);
        if (root->right) helper(root->right, res);
    }
};

迭代

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> res;
        if(!root) return res;
        stack<TreeNode*> stk;
        stk.push(root);
        while(!stk.empty()){
            TreeNode* temp = stk.top();
            stk.pop();
            res.push_back(temp->val);
            if (temp -> right) stk.push(temp->right);
            if (temp -> left) stk.push(temp->left);
        }
        return res;
    }
};
PreviousQ129. Sum Root to Leaf NumbersNext1.6 图

Last updated 5 years ago

Was this helpful?