N 叉树的层序遍历
vector< vector< int >> levelOrder ( Node* root) { vector< vector< int >> ret; if ( root == nullptr ) return ret; queue< Node* > q; q. push ( root) ; ret. push_back ( { root-> val} ) ; int size = 1 ; while ( ! q. empty ( ) ) { vector< int > v; while ( size-- ) { Node* front = q. front ( ) ; q. pop ( ) ; for ( Node* e : front-> children) { if ( e != nullptr ) { q. push ( e) ; v. push_back ( e-> val) ; } } } if ( ! v. empty ( ) ) { ret. push_back ( v) ; } size = q. size ( ) ; } return ret;
}
二叉树的锯齿形层序遍历
vector< vector< int >> zigzagLevelOrder ( TreeNode* root) { vector< vector< int >> ret; if ( root == nullptr ) return ret; queue< TreeNode* > q; q. push ( root) ; int level = 1 ; while ( ! q. empty ( ) ) { vector< int > v; int size = q. size ( ) ; while ( size-- ) { TreeNode* front = q. front ( ) ; q. pop ( ) ; v. push_back ( front-> val) ; if ( front-> left != nullptr ) { q. push ( front-> left) ; } if ( front-> right != nullptr ) { q. push ( front-> right) ; } } if ( level % 2 == 0 ) { reverse ( v. begin ( ) , v. end ( ) ) ; } ret. push_back ( v) ; ++ level; } return ret;
}
二叉树最大宽度
int widthOfBinaryTree ( TreeNode* root) { vector< pair< TreeNode* , unsigned int >> vp_prev = { { root, 1 } } ; unsigned int max_size = 0 ; while ( ! vp_prev. empty ( ) ) { max_size = max ( max_size, vp_prev. back ( ) . second - vp_prev. front ( ) . second + 1 ) ; vector< pair< TreeNode* , unsigned int >> vp; for ( auto & [ x, y] : vp_prev) { if ( x-> left != nullptr ) { vp. push_back ( { x-> left, 2 * y } ) ; } if ( x-> right != nullptr ) { vp. push_back ( { x-> right, 2 * y + 1 } ) ; } } vp_prev = vp; } return max_size;
}
在每个树行中找最大值
vector< int > largestValues ( TreeNode* root) { vector< int > ret; if ( root == nullptr ) { return ret; } queue< TreeNode* > q; q. push ( root) ; while ( ! q. empty ( ) ) { int max_val = INT_MIN; int size = q. size ( ) ; while ( size-- ) { TreeNode* front = q. front ( ) ; q. pop ( ) ; if ( front-> left != nullptr ) { q. push ( front-> left) ; } if ( front-> right != nullptr ) { q. push ( front-> right) ; } max_val = max ( max_val, front-> val) ; } ret. push_back ( max_val) ; } return ret;
}