LintCode 66: Binary Tree Preorder Traversal (二叉树遍历经典题!)

本文介绍了一种不使用递归实现二叉树前序遍历的方法,通过栈来跟踪节点,首先将根节点压入栈中,然后在循环中不断弹出栈顶元素并访问其值,接着按右子节点、左子节点的顺序将其非空子节点压入栈,直至栈空。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Binary Tree Preorder Traversal
    中文English
    Given a binary tree, return the preorder traversal of its nodes’ values.

Example
Example 1:

Input:{1,2,3}
Output:[1,2,3]
Explanation:
1
/
2 3
it will be serialized {1,2,3}
Preorder traversal
Example 2:

Input:{1,#,2,3}
Output:[1,2,3]
Explanation:
1

2
/
3
it will be serialized {1,#,2,3}
Preorder traversal
Challenge
Can you do it without recursion?

Notice
The first data is the root node, followed by the value of the left and right son nodes, and “#” indicates that there is no child node.
The number of nodes does not exceed 20.

解法1:参考了网上的模板。思路如下:
遍历顺序为根、左、右

  1. 如果root非空,将root加入到栈中。
  2. 如果栈不空,弹出出栈顶节点,将其值加加入到数组中。
    I. 如果该节点的右子树不为空,将右子节点加入栈中。
    II. 如果左子节点不为空,将左子节点加入栈中。
  3. 重复2), 直到栈空。

注意:
1) 这里的if 都没有else。
2) current=stack.top()后,stack马上就pop(), 与inorder和postorder traversal不一样。
3) 弹出栈顶节点后,先加右节点入栈,再加左节点入栈。

代码如下:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param root: A Tree
     * @return: Preorder in ArrayList which contains node values.
     */
    vector<int> preorderTraversal(TreeNode * root) {
        if (!root) return vector<int>();
        stack<TreeNode *> s;
        vector<int> result;
        
        s.push(root);
        while(!s.empty()) {
            TreeNode * current = s.top();
            result.push_back(current->val);
            s.pop();
            if (current->right) {
                s.push(current->right);
            }
            if (current->left) {
                s.push(current->left);
            }
        }
        return result;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值