144. Binary Tree Preorder Traversal
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了144. Binary Tree Preorder Traversal相关的知识,希望对你有一定的参考价值。
Given a binary tree, return the preorder traversal of its nodes‘ values.
For example:
Given binary tree {1,#,2,3},
return [1,2,3].
解题思路:
题目很简单,就是求一个二叉树的前序遍历。。使用栈实现递归过程。。。这里分别给出保存TreeNode的栈和保存TreeNode指针的栈。。
/** * 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; stack<TreeNode>s; if(root==NULL)return res; s.push(*(root)); while(!s.empty()){ TreeNode tmp=s.top(); s.pop(); res.push_back(tmp.val); if(tmp.right!=NULL)s.push(*(tmp.right)); if(tmp.left!=NULL)s.push(*(tmp.left)); } return 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; stack<TreeNode*>s; if(root==NULL)return res; s.push(root); while(!s.empty()){ TreeNode* tmp=s.top(); s.pop(); res.push_back(tmp->val); if(tmp->right!=NULL)s.push(tmp->right); if(tmp->left!=NULL)s.push(tmp->left); } return res; } }; |
java如果使用栈或者递归方法,耗时2ms,在discuss那里看到不用stack,用rights数组保存遍历过程中遇到的右结点,当当前结点的左结点为空,则从rights数组中找到最近的右结点。。。该方法耗费空间。。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer>order=new ArrayList<Integer>(); List<TreeNode>rights=new ArrayList<TreeNode>(); if(root==null)return order; TreeNode cur=root; int ind=-1; while(cur!=null){ order.add(cur.val); if(cur.right!=null){ ind++; rights.add(ind,cur.right); } if(cur.left!=null)cur=cur.left; else{ cur=ind<0?null:rights.get(ind); ind--; }
} return order; } } |
以上是关于144. Binary Tree Preorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal
144. Binary Tree Preorder Traversal