二叉树遍历
前、中、后序遍历的递归方法:
【Leetcode 94. 二叉树的中序遍历】
class Solution {
public :
vector< int > Result;
vector< int > inorderTraversal ( TreeNode* root) {
if ( root != nullptr )
{
inorderTraversal ( root-> left) ;
Result. push_back ( root-> val) ;
inorderTraversal ( root-> right) ;
}
return Result;
}
} ;
前序遍历非递归方法:
stack< TreeNode* > st;
vector< int > vec;
st. push ( root) ;
while ( ! st. empty ( ) )
{
TreeNode* t = st. top ( ) ;
vec. push_back ( t -> val) ;
st. pop ( ) ;
if ( t -> right != nullptr ) st. push ( t -> right) ;
if ( t -> left != nullptr ) st. push ( t -> left) ;
}
中序遍历非递归方法:
【Leetcode 98. 验证二叉搜索树】
stack< TreeNode* > st;
vector< int > vec;
TreeNode* t = root;
while ( t != nullptr || ! st. empty ( ) )
{
if ( t != nullptr )
{
st. push ( t) ;
t = t -> left;
}
else
{
TreeNode* p = st. top ( ) ;
st. pop ( ) ;
vec. push_back ( p -> val) ;
t = p -> right;
}
}
层序遍历方法:
【Leetcode 102. 二叉树的层序遍历】
class Solution {
public :
vector< vector< int >> vvi;
vector< vector< int >> levelOrder ( TreeNode* root) {
queue< TreeNode* > q;
q. push ( root) ;
int layerNum = 0 ;
while ( ! q. empty ( ) )
{
layerNum = q. size ( ) ;
vector< int > vt;
if ( root == nullptr ) break ;
for ( int i = 0 ; i < layerNum; i++ )
{
TreeNode* first = q. front ( ) ;
if ( first-> left != nullptr ) q. push ( first-> left) ;
if ( first-> right != nullptr ) q. push ( first-> right) ;
vt. push_back ( first-> val) ;
q. pop ( ) ;
}
vvi. push_back ( vt) ;
}
return vvi;
}
} ;
其他
class Solution {
public :
bool hasPathSum ( TreeNode* root, int targetSum) {
if ( root == nullptr ) return false ;
if ( targetSum - root-> val == 0 && root-> left == nullptr && root-> right == nullptr )
return true ;
return hasPathSum ( root-> left, targetSum - root-> val) || hasPathSum ( root-> right, targetSum - root-> val) ;
}
} ;
class Solution {
public :
TreeNode* lowestCommonAncestor ( TreeNode* root, TreeNode* p, TreeNode* q) {
if ( root == NULL ) return NULL ;
TreeNode* ans = root;
while ( true )
{
if ( p -> val > ans -> val && q -> val > ans -> val)
ans = ans -> right;
else if ( p -> val < ans -> val && q -> val < ans -> val)
ans = ans -> left;
else
break ;
}
return ans;
}
} ;
class Solution {
public :
vector< int > vec;
int findTargetNode ( TreeNode* root, int cnt) {
if ( root != NULL )
{
findTargetNode ( root -> right, cnt) ;
vec. push_back ( root -> val) ;
findTargetNode ( root -> left, cnt) ;
}
if ( vec. size ( ) >= cnt)
return vec[ cnt - 1 ] ;
return - 1 ;
}
} ;